Intlayerの今後のリリースに関する通知を受け取る
    作成:2024-08-11最終更新:2025-06-29

    React 統合: useI18n フック ドキュメント

    このセクションでは、React アプリケーション内で useI18n フックを使用して効率的なコンテンツのローカライズを実現する方法について詳細に説明します。

    React での useI18n のインポート

    useI18n フックは、以下のようにコンテキストに応じて React アプリケーションにインポートおよび統合できます。

    • クライアントコンポーネント:

      typescript
      import { useI18n } from "react-intlayer"; // クライアントサイドの React コンポーネントで使用
    • サーバーコンポーネント:

    パラメータ

    このフックは2つのパラメータを受け取ります:

    1. namespace:翻訳キーのスコープを指定する辞書の名前空間。
    2. locale(オプション):希望するロケール。指定しない場合は、コンテキストのロケールがデフォルトで使用されます。

    辞書

    すべての辞書キーは、型安全性を高めエラーを防ぐためにコンテンツ宣言ファイル内で宣言する必要があります。設定手順はこちらで確認できます。

    Reactでの使用例

    Reactコンポーネント内でuseI18nフックを使用する例:

    src/App.tsx
    import type { FC } from "react";import { ClientComponentExample, ServerComponentExample } from "@components";import { IntlayerProvider } from "react-intlayer";import { useI18n, IntlayerServerProvider } from "react-intlayer/server";import { Locales } from "intlayer";const App: FC<{ locale: Locales }> = ({ locale }) => {  const t = useI18n("home-page", locale);  return (    <>      <p>{t("introduction")}</p>      <IntlayerProvider locale={locale}>        <ClientComponentExample />      </IntlayerProvider>      <IntlayerServerProvider locale={locale}>        <ServerComponentExample />      </IntlayerServerProvider>    </>  );};
    src/components/ComponentExample.tsx
    import type { FC } from "react";import { useI18n } from "react-intlayer";const ComponentExample: FC = () => {  const t = useI18n("component-example");  return (    <div>      <h1>{t("title")}</h1> {/* タイトルを表示 */}      <p>{t("description")}</p> {/* 説明を表示 */}    </div>  );};
    src/components/ServerComponentExample.tsx
    import { useI18n } from "react-intlayer/server";const ServerComponentExample = () => {  const t = useI18n("server-component");  return (    <div>      <h1>{t("title")}</h1> {/* タイトルを表示 */}      <p>{t("description")}</p> {/* 説明を表示 */}    </div>  );};

    属性の取り扱い

    属性をローカライズする際は、翻訳値に適切にアクセスしてください:

    jsx
    <!-- アクセシビリティ属性(例:aria-label)には、純粋な文字列が必要なため .value を使用します --><button aria-label={t("button.ariaLabel").value}>{t("button.text")}</button>

    追加リソース

    • Intlayer ビジュアルエディター: より直感的なコンテンツ管理体験のために、ビジュアルエディターのドキュメントはこちらをご参照ください。

    このセクションでは、Reactアプリケーションにおける useI18n フックの統合について具体的に説明しており、ローカライズプロセスを簡素化し、異なるロケール間でのコンテンツの一貫性を確保します。

    ドキュメント履歴

    • 6.0.0 - 2025-06-29: useI18n フックのドキュメント初版作成
    Intlayerの今後のリリースに関する通知を受け取る