React統合: useDictionaryフックドキュメント
このセクションでは、Reactアプリケーション内でuseDictionaryフックを使用するための詳細なガイダンスを提供します。これにより、ビジュアルエディタを使用せずに効率的にローカライズされたコンテンツを処理できます。
ReactでのuseDictionaryのインポート
useDictionaryフックは、コンテキストに基づいてインポートすることでReactアプリケーションに統合できます。
クライアントコンポーネント:
typescriptimport { useDictionary } from "next-intlayer"; // クライアントサイドのReactコンポーネントで使用
サーバーコンポーネント:
typescriptimport { useDictionary } from "next-intlayer/server"; // サーバーサイドのReactコンポーネントで使用
パラメータ
このフックは2つのパラメータを受け取ります:
- dictionary: 特定のキーに対するローカライズされたコンテンツを含む宣言された辞書オブジェクト。
- locale (オプション): 希望するロケール。指定されていない場合は現在のコンテキストのロケールがデフォルトになります。
辞書
すべての辞書オブジェクトは、型安全性を確保し、実行時エラーを防ぐために構造化されたコンテンツファイルで宣言する必要があります。セットアップ手順はこちらをご覧ください。以下はコンテンツ宣言の例です:
component.content.ts
import { t, type Dictionary } from "intlayer";const exampleContent = { key: "component-example", content: { title: t({ en: "Client Component Example", fr: "Exemple de composant client", es: "Ejemplo de componente cliente", }), content: t({ en: "This is the content of a client component example", fr: "Ceci est le contenu d'un exemple de composant client", es: "Este es el contenido de un ejemplo de componente cliente", }), },} satisfies Dictionary;export default exampleContent;
Reactクライアントコンポーネントでの使用例
以下は、ReactコンポーネントでuseDictionaryフックを使用する例です:
ClientComponentExample.tsx
"use client";import type { FC } from "react";import { useDictionary } from "next-intlayer";import clientComponentExampleContent from "./component.content";const ClientComponentExample: FC = () => { const { title, content } = useDictionary(clientComponentExampleContent); return ( <div> <h1>{title}</h1> <p>{content}</p> </div> );};
Reactサーバーコンポーネントでの使用例
IntlayerServerProviderの外部でuseDictionaryフックを使用する場合、コンポーネントをレンダリングする際にロケールを明示的に指定する必要があります:
ServerComponentExample.tsx
import type { FC } from "react";import { useDictionary } from "next-intlayer/server";import clientComponentExampleContent from "./component.content";const ServerComponentExample: FC = () => { const { content } = useDictionary(clientComponentExampleContent); return ( <div> <h1>{content.title}</h1> <p>{content.content}</p> </div> );};
属性に関する注意点
ビジュアルエディタを使用する統合とは異なり、buttonTitle.valueのような属性はここでは適用されません。代わりに、コンテンツで宣言されたローカライズされた文字列に直接アクセスします。
jsx
<button title={content.title}>{content.content}</button>
追加のヒント
- 型安全性: 辞書を定義する際は常にDictionaryを使用して型安全性を確保してください。
- ローカライズの更新: コンテンツを更新する際は、すべてのロケールが一貫していることを確認し、翻訳漏れを防いでください。
このドキュメントは、useDictionaryフックの統合に焦点を当てており、ビジュアルエディタ機能に依存せずにローカライズされたコンテンツを管理するための効率的なアプローチを提供します。
このドキュメントを改善するアイデアがある場合は、GitHubでプルリクエストを送信することで自由に貢献してください。
ドキュメントへのGitHubリンク