Helpers
useLocaleSelector
useLocaleSelector フックのAPIリファレンス
概要
このフックは、現在の locale、対応ロケールの一覧、useSetLocale フック、そして locale のプロパティを取得する関数を返します。
独自のロケール選択コンポーネントを作成する際に、手軽に使えるよう設計されています。
独自に実装しない場合は、代わりに <LocaleSelector> コンポーネントを使用できます。
リファレンス
戻り値
現在のlocale、対応ロケールの一覧、useSetLocaleフック、そして locale のプロパティを取得する関数を含むオブジェクト。
例
<LocaleSelector>
これは、<LocaleSelector> コンポーネントの実装例です。
export default function LocaleSelector({
  locales: _locales,
  ...props
}: {
  locales?: string[];
  [key: string]: any;
}): React.JSX.Element | null {
  // ロケールセレクター用のプロパティを取得
  const { locale, locales, setLocale, getLocaleProperties } = useLocaleSelector(
    _locales ? _locales : undefined
  );
  // 表示名を取得
  const getDisplayName = (locale: string) => {
    return capitalizeLanguageName(
      getLocaleProperties(locale).nativeNameWithRegionCode
    );
  };
  // ロケールが取得できない場合は、何も描画しないか適切に処理する
  if (!locales || locales.length === 0 || !setLocale) {
    return null;
  }
  return (
    <select
      {...props}
      // currentLocale が未定義の場合は空文字列をフォールバックとして使用
      value={locale || ''}
      onChange={(e) => setLocale(e.target.value)}
    >
      {/* ロケール未設定時の任意のフォールバック */}
      {!locale && <option value='' />}
      {locales.map((locale) => (
        <option key={locale} value={locale} suppressHydrationWarning>
          {getDisplayName(locale)}
        </option>
      ))}
    </select>
  );
}補足
- このフックはクライアントサイドでのみ動作します。
- ロケールコード文字列の詳細はこちらをご覧ください。
次のステップ
- <LocaleSelector>コンポーネントについて詳しく知る
- useLocaleフックについて詳しく知る
このガイドはどうでしたか?

