# General Translation React SDKs (gt-react, gt-next, gt-react-native): React Native クイックスタート
URL: https://generaltranslation.com/ja/docs/react/react-native-quickstart.mdx
Docs index: https://generaltranslation.com/llms.txt
Description: `gt-react-native` を使って React Native アプリに General Translation を追加する方法を、Expo と標準の React Native CLI の両方について説明します。

`gt-react-native` を使うと、React Native アプリに自動で国際化を導入できます。アプリのエントリポイントで General Translation を初期化し、React Native に必要なポリフィル用の Babel プラグインを追加して、アプリを [`GTProvider`](/docs/react/reference/components/gt-provider) でラップします。

このクイックスタートでは、Expo と標準の React Native CLI の両方を扱います。Web の React アプリについては、[React クイックスタート](/docs/react/react-quickstart) を参照してください。

<Callout type="warn">
  **警告:** `gt-react-native` は実験的機能であり、すべてのプロジェクトで動作するとは限りません。ネイティブモジュールを含むため、**Expo Go はサポートされていません**。開発用ビルドが必要です。
</Callout>

## クイックスタート [#quickstart]

パッケージをインストールし、設定ファイルを作成し、ポリフィルを設定し、翻訳ローダーを追加し、プロバイダーでGeneral Translationを初期化し、コンテンツを翻訳対象として指定して、翻訳を生成します。

### 1. `gt-react-native` をインストール

依存関係として `gt-react-native` を、開発依存関係として [`gt` CLI](/docs/cli/quickstart) をインストールします。

<Tabs items={['npm', 'yarn', 'bun', 'pnpm']}>
  <Tab value="npm">
    ```bash
    npm install gt-react-native && npm install gt --save-dev
    ```
  </Tab>

  <Tab value="yarn">
    ```bash
    yarn add gt-react-native && yarn add --dev gt
    ```
  </Tab>

  <Tab value="bun">
    ```bash
    bun add gt-react-native && bun add --dev gt
    ```
  </Tab>

  <Tab value="pnpm">
    ```bash
    pnpm add gt-react-native && pnpm add --save-dev gt
    ```
  </Tab>
</Tabs>

<Callout type="info">
  **注:** 標準の React Native CLI を使用している場合は、ネイティブモジュールをリンクするため、インストール後に `cd ios && pod install` を実行してください。
</Callout>

### 2. `gt.config.json` を作成する

プロジェクトルートに `gt.config.json` ファイルを作成します。このファイルでは、ソース言語、対象のロケール、そして翻訳ファイルの出力先を指定します。

```json title="gt.config.json"
{
  "defaultLocale": "en",
  "locales": ["es", "fr", "ja"],
  "files": {
    "gt": {
      "output": "src/_gt/[locale].json"
    }
  }
}
```

* `defaultLocale` — アプリの記述に使う言語。
* `locales` — 翻訳先の言語。[サポートされているロケール](/docs/platform/dashboard/reference/supported-locales) から選択します。
* `files.gt.output` — CLI が翻訳ファイルを書き出す場所。`[locale]` は各ロケールコードに置き換えられます。

### 3. ポリフィルを設定する

React Native の JavaScript ランタイムには、`gt-react-native` が必要とする `Intl` API が含まれていません。付属の Babel プラグインを追加し、`entryPointFilePath` でアプリのエントリファイルを指定してください。

<Tabs items={['Expo', 'React Native CLI']}>
  <Tab value="Expo">
    ```js title="babel.config.js"
    const { plugin: gtPlugin } = require('gt-react-native/plugin');
    const gtConfig = require('./gt.config.json');

    module.exports = function (api) {
      api.cache(true);
      return {
        presets: ['babel-preset-expo'],
        plugins: [
          [
            gtPlugin,
            {
              locales: [gtConfig.defaultLocale, ...gtConfig.locales],
              entryPointFilePath: require.resolve('expo-router/entry'),
            },
          ],
        ],
      };
    };
    ```
  </Tab>

  <Tab value="React Native CLI">
    ```js title="babel.config.js"
    const path = require('path');
    const { plugin: gtPlugin } = require('gt-react-native/plugin');
    const gtConfig = require('./gt.config.json');

    module.exports = {
      presets: ['module:@react-native/babel-preset'],
      plugins: [
        [
          gtPlugin,
          {
            locales: [gtConfig.defaultLocale, ...gtConfig.locales],
            entryPointFilePath: path.resolve(__dirname, 'index.js'),
          },
        ],
      ],
    };
    ```
  </Tab>
</Tabs>

このプラグインは**名前付きエクスポート**なので、`const { plugin: gtPlugin } = require('gt-react-native/plugin')` のように分割代入してください。必要な `@formatjs` のポリフィルは、このプラグインによってエントリファイルの先頭に挿入されます。Metro がリージョン付きロケールのロケールデータを解決できない場合は、[手動でのポリフィル設定](/docs/react/react-native/plugin#how-it-works) に従い、アプリのリージョン付きロケールは変更しないでください。

### 4. 翻訳ローダーを作成する

Metro (React Native のバンドラー) は動的インポートをサポートしていないため、各ロケールを対応する翻訳ファイルに静的な `require` 呼び出しでマッピングします。

```ts title="loadTranslations.ts"
const translations: Record<string, unknown> = {
  es: require('./src/_gt/es.json'),
  fr: require('./src/_gt/fr.json'),
  ja: require('./src/_gt/ja.json'),
};

export function loadTranslations(locale: string) {
  return translations[locale] ?? {};
}
```

[`npx gt translate`](/docs/cli/reference/commands/translate) を実行すると、CLI によってこれらのファイルが生成されます。

<Callout type="warn">
  **警告:** これらのファイルは作成するまで存在せず、作成されるまでは Metro はアプリをバンドルしません。アプリを起動する前に、[`npx gt generate`](/docs/cli/reference/commands/generate) (API キー不要) または [`npx gt translate`](/docs/cli/reference/commands/translate) (認証情報が必要) を実行してください。
</Callout>

### 5. General Translation を初期化してプロバイダーを追加する

レンダリングの前に、アプリのエントリポイントで [`initializeGT`](/docs/react/reference/config#initialize) を一度呼び出してから、アプリを [`GTProvider`](/docs/react/reference/components/gt-provider) でラップします。Web パッケージとは異なり、[`GTProvider`](/docs/react/reference/components/gt-provider) は内部で翻訳を読み込むため、`translations` prop を渡す必要はなく、通常は `locale` も渡す必要がありません。`locale` は自動検出されます。検出結果を上書きしたい場合は、任意の `locale` prop を指定することもできます。

<Tabs items={['Expo', 'React Native CLI']}>
  <Tab value="Expo">
    ```tsx title="app/_layout.tsx"
    import { Slot } from 'expo-router';
    import { GTProvider, initializeGT } from 'gt-react-native';
    import gtConfig from '../gt.config.json';
    import { loadTranslations } from '../loadTranslations';

    // モジュールレベルで一度だけ初期化
    initializeGT({
      ...gtConfig,
      loadTranslations,
      projectId: process.env.EXPO_PUBLIC_GT_PROJECT_ID,
      devApiKey: process.env.EXPO_PUBLIC_GT_DEV_API_KEY,
    });

    export default function RootLayout() {
      return (
        <GTProvider>
          <Slot />
        </GTProvider>
      );
    }
    ```
  </Tab>

  <Tab value="React Native CLI">
    ```js title="index.js"
    import { AppRegistry } from 'react-native';
    import { initializeGT } from 'gt-react-native';
    import App from './App';
    import { name as appName } from './app.json';
    import gtConfig from './gt.config.json';
    import { loadTranslations } from './loadTranslations';

    // アプリを登録する前に一度だけ初期化
    initializeGT({ ...gtConfig, loadTranslations });

    AppRegistry.registerComponent(appName, () => App);
    ```

    ```tsx title="App.tsx"
    import { GTProvider } from 'gt-react-native';
    import Home from './src/Home';

    export default function App() {
      return (
        <GTProvider>
          <Home />
        </GTProvider>
      );
    }
    ```
  </Tab>
</Tabs>

<Callout type="info">
  **注:** `projectId` と `devApiKey` オプションを指定すると、開発中にオンデマンド翻訳を有効にできます。Expo では、`EXPO_PUBLIC_` プレフィックスを付けて公開してください。
</Callout>

### 6. 翻訳対象としてコンテンツを指定する

JSX をインプレースで翻訳するには、[`<T>`](/docs/react/reference/components/t) コンポーネントでラップします。`placeholder` や `accessibilityLabel` の値のような単独の string には、[`useGT`](/docs/react/reference/hooks/use-gt) フックを使用します。言語切り替え機能を作成するには、[`useLocaleSelector`](/docs/react/reference/hooks/use-locale-selector) フックを使用します。`gt-react-native` には、あらかじめ用意されたセレクターコンポーネントは含まれていません。

```tsx title="src/Home.tsx"
import { Text, View, Pressable, TextInput } from 'react-native';
import { T, useGT, useLocaleSelector } from 'gt-react-native';

export default function Home() {
  const gt = useGT();
  const { locales, locale, setLocale } = useLocaleSelector();

  return (
    <View>
      <View style={{ flexDirection: 'row', gap: 8 }}>
        {locales.map((l) => (
          <Pressable key={l} onPress={() => setLocale(l)}>
            <Text style={{ fontWeight: l === locale ? 'bold' : 'normal' }}>
              {l}
            </Text>
          </Pressable>
        ))}
      </View>
      <T>
        <Text>Welcome to my app</Text>
      </T>
      <TextInput accessibilityLabel={gt('Email input field')} />
    </View>
  );
}
```

[`useGT()`](/docs/react/reference/hooks/use-gt) は翻訳関数を直接返すので、`const gt = useGT();` のように呼び出します。

### 7. 翻訳を生成する

CLI を実行し、General Translation API を通じてプロジェクトを翻訳します。

```bash
npx gt translate
```

本番ビルドで常に最新の翻訳が使われるよう、このコマンドをビルドスクリプトに追加してください：

```json title="package.json"
{
  "scripts": {
    "build": "npx gt translate && <your build command>"
  }
}
```

<Callout type="info">
  **注:** [`npx gt translate`](/docs/cli/reference/commands/translate) を使うには、環境変数に `GT_PROJECT_ID` と `GT_API_KEY` として設定したプロジェクト ID と本番用の API キーが必要です。取得するには、[`npx gt auth`](/docs/cli/reference/commands/auth) を実行するか、[ダッシュボード](/docs/platform/dashboard/get-started) にアクセスしてください。
</Callout>

## Next steps

- /docs/react/guides/translating-jsx
- /docs/react/guides/translating-strings
- /docs/react/guides/managing-locales
- /docs/react/guides/formatting-variables

## Sitemap

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