# General Translation React SDKs (gt-react, gt-next, gt-react-native): ロケールの管理
URL: https://generaltranslation.com/ja/docs/react/guides/managing-locales.mdx
Docs index: https://generaltranslation.com/llms.txt
Description: 対応ロケールを設定し、React の言語切り替え機能を構築し、アクティブなロケールを取得または変更する方法。

`en-US` や `fr` などのロケールコードは、ユーザーが選択した言語を適切な翻訳とフォーマット規則に結び付けます。

アプリで対応するロケールを宣言し、ユーザーがその中から選択できるようにし、UI で言語固有の動作が必要な場合はアクティブなロケールを取得します。

## ロケールの状態を理解する [#locale-state]

* **デフォルトロケール:** ソースコンテンツの言語であり、対応するロケールがない場合に使用される最終的なフォールバックです。
* **対応ロケール:** デフォルトロケールとターゲットロケールを含む、ユーザーが選択できるすべてのロケールです。
* **アクティブなロケール:** URL、保存された設定、ブラウザ設定、またはデフォルトに基づいて選択される対応ロケールです。

## 対応ロケールを宣言する [#declare]

[`defaultLocale`](/docs/react/reference/config#default-locale)を設定し、対象の[`locales`](/docs/react/reference/config#locales)を `gt.config.json` に記載します。

```json title="gt.config.json"
{
  "defaultLocale": "en",
  "locales": ["es", "fr", "de"]
}
```

React、TanStack Start、React Native では、これらの値を初期化時の呼び出しに渡します。Next.js では、[`withGTConfig`](/docs/react/nextjs/config)が `gt.config.json` を自動的に読み込みます。各フレームワークのセットアップについては、[General Translation の設定](/docs/react/guides/configuring)を参照してください。

## 言語切り替え機能を追加する [#switcher]

インターフェースに最も適したシンプルな方法を選択してください。

* React、Next.js、TanStack Start で既成のドロップダウンを使用するには、[`<LocaleSelector>`](/docs/react/reference/components/locale-selector) を使用します。
* サポートされている任意のフレームワークでカスタムの言語切り替え機能を作成するには、[`useLocaleSelector`](/docs/react/reference/hooks/use-locale-selector) を使用します。
* ボタンなど、指定したロケールに切り替えるコントロールには、[`useSetLocale`](/docs/react/reference/hooks/use-set-locale) を使用します。

### すぐに使えるセレクターを使用する

client component で [`<LocaleSelector>`](/docs/react/reference/components/locale-selector) をレンダーします。props を指定しない場合、設定済みのすべてのロケールが一覧表示され、ユーザーが項目を選ぶとアクティブなロケールが切り替わります。

<Tabs items={['React', 'Next.js', 'TanStack Start', 'React Native']}>
  <Tab value="React">
    ```tsx
    import { LocaleSelector } from 'gt-react';

    <LocaleSelector />;
    ```
  </Tab>

  <Tab value="Next.js">
    ```tsx
    import { LocaleSelector } from 'gt-next';

    <LocaleSelector />;
    ```
  </Tab>

  <Tab value="TanStack Start">
    ```tsx
    import { LocaleSelector } from 'gt-tanstack-start';

    <LocaleSelector />;
    ```
  </Tab>

  <Tab value="React Native">
    *注: React Native は [`<LocaleSelector>`](/docs/react/reference/components/locale-selector) をエクスポートしていません。以下のように、[`useLocaleSelector`](/docs/react/reference/hooks/use-locale-selector) を使ってカスタムの切り替え機能を実装してください。*
  </Tab>
</Tabs>

### カスタム言語切り替え機能を作成する

[`useLocaleSelector`](/docs/react/reference/hooks/use-locale-selector) は、アクティブなロケール、利用可能なロケール、設定関数、ローカライズされた表示名を1つのhookで提供します。使用するコントロールはフレームワークに合わせて選択してください。

<Tabs items={['React', 'Next.js', 'TanStack Start', 'React Native']}>
  <Tab value="React">
    ```tsx
    import { useLocaleSelector } from 'gt-react';

    function Switcher() {
      const { locale, locales, setLocale, getLocaleProperties } =
        useLocaleSelector();

      return (
        <select value={locale} onChange={(e) => setLocale(e.target.value)}>
          {locales.map((localeCode) => (
            <option key={localeCode} value={localeCode}>
              {getLocaleProperties(localeCode).nativeNameWithRegionCode}
            </option>
          ))}
        </select>
      );
    }
    ```
  </Tab>

  <Tab value="Next.js">
    ```tsx
    'use client';

    import { useLocaleSelector } from 'gt-next';

    function Switcher() {
      const { locale, locales, setLocale, getLocaleProperties } =
        useLocaleSelector();

      return (
        <select value={locale} onChange={(e) => setLocale(e.target.value)}>
          {locales.map((localeCode) => (
            <option key={localeCode} value={localeCode}>
              {getLocaleProperties(localeCode).nativeNameWithRegionCode}
            </option>
          ))}
        </select>
      );
    }
    ```
  </Tab>

  <Tab value="TanStack Start">
    ```tsx
    import { useLocaleSelector } from 'gt-tanstack-start';

    function Switcher() {
      const { locale, locales, setLocale, getLocaleProperties } =
        useLocaleSelector();

      return (
        <select value={locale} onChange={(e) => setLocale(e.target.value)}>
          {locales.map((localeCode) => (
            <option key={localeCode} value={localeCode}>
              {getLocaleProperties(localeCode).nativeNameWithRegionCode}
            </option>
          ))}
        </select>
      );
    }
    ```
  </Tab>

  <Tab value="React Native">
    ```tsx
    import { Button, View } from 'react-native';
    import { useLocaleSelector } from 'gt-react-native';

    function Switcher() {
      const { locale, locales, setLocale, getLocaleProperties } =
        useLocaleSelector();

      return (
        <View>
          {locales.map((localeCode) => (
            <Button
              key={localeCode}
              title={getLocaleProperties(localeCode).nativeNameWithRegionCode}
              disabled={localeCode === locale}
              onPress={() => setLocale(localeCode)}
            />
          ))}
        </View>
      );
    }
    ```
  </Tab>
</Tabs>

Reactウェブアプリで直接ロケールを切り替えるだけでよい場合は、[`useSetLocale`](/docs/react/reference/hooks/use-set-locale) を呼び出してください。

```tsx
import { useSetLocale } from 'gt-react';

function FrenchButton() {
  const setLocale = useSetLocale();
  return <button onClick={() => setLocale('fr')}>Français</button>;
}
```

## ロケールの選択を保存してルーティングする [#persistence]

[`<LocaleSelector>`](/docs/react/reference/components/locale-selector)、[`useLocaleSelector`](/docs/react/reference/hooks/use-locale-selector)、または [`useSetLocale`](/docs/react/reference/hooks/use-set-locale) でロケールを変更すると、その選択が保存され、新しい翻訳はフレームワークごとに異なる方法で適用されます。

* **React:** ロケールをcookieに保存し、デフォルトではページを再読み込みします。カスタムproviderの再読み込みcallbackを使用すると、ページ全体の再読み込みを置き換えられます。
* **Next.js App Router:** ロケールをcookieに保存し、通常はサーバーコンポーネントツリーを更新します。ロケールルーティングが有効な場合、非デフォルトロケールに解決されるURLからデフォルトロケールに切り替えると、ミドルウェアがロケールプレフィックスを削除できるようドキュメントを再読み込みます。すでにデフォルトロケールに解決されるURLでは、更新のみ行われます。
* **Next.js Pages Router:** ロケールをcookieに保存します。providerの再読み込みcallbackを設定すると、Pages Routerでナビゲートして選択したロケールのページpropsを取得します。
* **TanStack Start:** ロケールをcookieに保存し、ページを再読み込みします。[`localeRouting`](/docs/react/reference/config#locale-routing) を有効にすると、対応するロケールのpathnameにナビゲートします。
* **React Native:** ロケールをネイティブストレージ (React Native Webでは `localStorage`) に保存し、providerのstateを更新してロケールの翻訳を読み込み、ブラウザでのナビゲーションなしに再レンダリングします。

公開ページでは、ロケールベースのURLにより、各言語版を共有可能かつインデックス可能にできます。ルーティングはフレームワーク固有のガイドで設定してください。

* [Next.js App Router ミドルウェア](/docs/react/nextjs/app-router-middleware)
* [Next.js Pages Router ロケールルーティング](/docs/react/nextjs/pages-router-middleware)
* [TanStack Start ロケールルーティング](/docs/react/tanstack-start/setup#locale-routing)

## アクティブなロケールを読み取る [#read]

言語固有の UI をレンダリングする際は、ロケールフックを使用します。

* [`useLocale`](/docs/react/reference/hooks/use-locale) はアクティブなロケールコードを返します。
* [`useDefaultLocale`](/docs/react/reference/hooks/use-default-locale) はソースロケールを返します。
* [`useLocales`](/docs/react/reference/hooks/use-locales) はサポートされているすべてのロケールコードを返します。
* [`useLocaleDirection`](/docs/react/reference/hooks/use-locale-direction) は、ページレイアウト用の `'ltr'` または `'rtl'` を返します。
* [`useLocaleProperties`](/docs/react/reference/hooks/use-locale-properties) は、ロケールの名前、ネイティブ名、リージョン、スクリプト、その他の表示用メタデータを返します。

*注: `gt-tanstack-start` は現在 [`useLocaleDirection`](/docs/react/reference/hooks/use-locale-direction) と [`useLocaleProperties`](/docs/react/reference/hooks/use-locale-properties) をエクスポートしていません。代わりに、`generaltranslation` の [`getLocaleProperties`](/docs/platform/core/reference/utility-functions/locales/get-locale-properties) を使ってロケールのメタデータを取得してください。*

Next.js では、これらのフックは同期的な App Router サーバーコンポーネントで動作します。非同期コンポーネントでは、`gt-next/server` の [`getLocale`](/docs/react/nextjs/reference/functions/get-locale) と [`getLocaleDirection`](/docs/react/nextjs/reference/functions/get-locale-direction) を呼び出します。

```tsx
import { getLocale, getLocaleDirection } from 'gt-next/server';

async function Layout() {
  const locale = await getLocale();
  const dir = await getLocaleDirection();
  return <html lang={locale} dir={dir} />;
}
```

ロケールのマッチングとフォールバックの動作については、[`useLocale`](/docs/react/reference/hooks/use-locale) リファレンスページを参照してください。

## Next steps

- /docs/react/guides/translating-jsx
- /docs/react/guides/translating-strings
- /docs/react/guides/configuring
- /docs/react/guides/storing-translations

## Sitemap

See the full [sitemap](https://generaltranslation.com/sitemap.md) for all pages.
