useTranslations
useTranslations フックのAPIリファレンス
概要
useTranslations は、translation dictionary に定義された文字列の翻訳を取得するためのフックです。
<GTProvider> でラップされたコンポーネント内で使用する必要があります。
const d = useTranslations(); // 翻訳関数を取得
d('greeting.hello'); // idを渡して翻訳を取得useTranslations は、翻訳用コンテンツを管理するためにdictionaryを使用します。
これは、翻訳に<T>コンポーネントを使う方法とは異なります。
翻訳に <T> コンポーネントのみを使用する予定であれば、このドキュメントは対象外です。
リファレンス
パラメータ
Prop
Type
説明
| Prop | 説明 | 
|---|---|
| id | すべての翻訳キーの先頭に付与する任意のプレフィックス。ネストされたdictionaryの値を扱う際に便利です。 | 
返り値
id を受け取り、対応する Entry の翻訳を返す翻訳関数 d
(id: string, options?: DictionaryTranslationOptions) => React.ReactNode| 名前 | 型 | 説明 | 
|---|---|---|
| id | string | 翻訳対象のEntryのid | 
| options? | DictionaryTranslationOptions | dの挙動をカスタマイズするための翻訳options。 | 
例例
dictionary の基本的な使い方
dictionary 内のすべての Entry が翻訳されます。
const dictionary = {
  greeting: "こんにちは、Bob", 
};
export default dictionary;これらのエントリにアクセスするには、useTranslations を呼び出します。
この呼び出しは、dictionary にある翻訳キーを受け取る関数を返します。
dictionary は GTProvider コンポーネントに渡す必要があります。
import { useTranslations } from 'gt-react';
import dictionary from "./dictionary.json"
export default function TranslateGreeting() {
  const d = useTranslations(); 
  return (
    <GTProvider dictionary={dictionary}>
      <p>
        {d('greeting')} // [!code highlight]
      </p>
    </GTProvider>
  );
}variables を使用する
値を渡すには、(1) 識別子を割り当て、(2) d 関数を呼び出すときにその識別子を参照する必要があります。
この例では、翻訳に variables を渡すために {} を使用します。
dictionary では、識別子 {userName} を割り当てます。
const dictionary = {
  greeting: "こんにちは、{userName}さん!", 
};
export default dictionary;import { useTranslations } from 'gt-react';
export default function TranslateGreeting() {
  const d = useTranslations();
  
  // Hello Alice!
  const greetingAlice = d('greeting', { userName: "Alice" }); 
  return (
    <p>
      {greetingAlice} // Hello, Alice // [!code highlight]
    </p>
  );
}プレフィックスの使用
dictionary の一部だけを翻訳するために、プレフィックスを利用できます。
const dictionary = {
  prefix1: { 
    prefix2: { 
      greeting: "こんにちは、Bob",
    }
  }
};
export default dictionary;useTranslations フックに 'prefix1.prefix2' を value として設定したため、すべてのキーに prefix1.prefix2 がプレフィックスされます。
import { useTranslations } from 'gt-react';
export default function UserDetails() {
  const d = useTranslations('prefix1.prefix2'); 
  return (
    <div>
      <p>{d('greeting')}</p> // greeting => prefix1.prefix2.greeting // [!code highlight]
    </div>
  );
}注意事項
- useTranslations関数を使うと、dictionary の翻訳にアクセスできます。
- useTranslationsフックは、- <GTProvider>コンポーネント でラップされたコンポーネント内でのみ使用できます。
次のステップ
このガイドはどうでしたか?

