Helpers

useLocaleSelector

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

概要

このフックは現在のlocale、対応ロケール(locales)の一覧、そしてuseSetLocaleフックを返します。 独自のロケールセレクターコンポーネントを作成する際に手軽に利用できるよう設計されています。

独自に実装したくない場合は、代わりに<LocaleSelector>コンポーネントを使用できます。

リファレンス

戻り値

現在の locale、locales の一覧、そして useSetLocale フックを含むオブジェクト。

<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>
  );
}

注意

  • このフックはクライアントサイド専用です。
  • ロケールコード文字列の詳細はこちらをご覧ください。

次のステップ

このガイドはどうでしたか?

useLocaleSelector