Dictionary Translations

useTranslations

useTranslations フックの APIリファレンス

概要

useTranslations は、translation dictionary から文字列の翻訳を取得するために使用します。

<GTProvider> でラップされたコンポーネント内で使用する必要があります。

const d = useTranslations(); // 翻訳関数を取得する
d('greeting.hello'); // 翻訳を取得するために id を渡す

非同期コンポーネントについては、getTranslationsを参照してください。

getTranslationsuseTranslations は、翻訳用コンテンツを管理するために dictionary を使用します。 これは、翻訳に <T> コンポーネントを使用する方法とは異なります。 翻訳に <T> コンポーネントのみを使用する場合は、このドキュメントは対象外です。

リファレンス

パラメータ

Prop

Type

説明

Prop説明
idすべての翻訳キーの先頭に付与する任意のプレフィックス。ネストされた dictionary の値を扱う際に便利です。

戻り値

id を受け取って対応する Entry の翻訳を返す翻訳関数 d

(id: string, options?: DictionaryTranslationOptions) => React.ReactNode
名称Type説明
idstring翻訳対象のEntryのid
options?DictionaryTranslationOptionsd の動作をカスタマイズするための翻訳options。

dictionary の基本的な使い方

dictionary の各 Entry はすべて翻訳されます。

dictionary.jsx
const dictionary = {
  greeting: "こんにちは、Bobさん", 
};
export default dictionary;

クライアント側でこれらのエントリにアクセスする場合は、useTranslations を呼び出します。 これにより、dictionary の翻訳キーを受け取る関数が返されます。

TranslateGreeting.jsx
import { useTranslations } from 'gt-next';

export default async function TranslateGreeting() {
  const d = useTranslations(); 
  return (
    <p>
      {d('greeting')} // こんにちは、アリス // [!code highlight]
    </p>
  );
}

variables を使用する

値を渡すには、(1) 識別子を割り当て、(2) d 関数を呼び出す際にその識別子を参照する必要があります。

この例では、翻訳に variables を渡すために {} を使用します。 dictionary では、識別子 {userName} を割り当てます。

dictionary.jsx
const dictionary = {
  greeting: "こんにちは、{userName}さん!", 
};
export default dictionary;
src/server/TranslateGreeting.jsx
import { useTranslations } from 'gt-next';

export default async function TranslateGreeting() {
  const d = useTranslations();
  
  // アリスさん、こんにちは!
  const greetingAlice = d('greeting', { userName: "Alice" }); 

  return (
    <p>
      {greetingAlice}
    </p>
  );
}

プレフィックスの使用

プレフィックスを使うと、dictionary の一部だけを翻訳できます。

dictionary.jsx
const dictionary = {
  prefix1: { 
    prefix2: { 
      greeting: "こんにちは、ボブ",
    }
  }
};
export default dictionary;

useTranslations フックに value として 'prefix1.prefix2' を追加したため、すべてのキーに prefix1.prefix2 がプレフィックスとして付きます。

UserDetails.jsx
import { useTranslations } from 'gt-next';

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> コンポーネントでラップされたコンポーネント内でのみ使用できます。

次のステップ

このガイドはいかがですか?