【React】react-i18next ~ 多言語対応 ~

◾️はじめに

reactでの多言語対応についてメモ。

目次

【1】reactでの多言語対応
 1)補足:i18n
【2】作業の流れ
 1)ライブラリのインストール
 2)翻訳ファイル作成
 3)i18next の初期設定
 4)React コンポーネントでの使用方法
【3】エラー「Failed to resolve import "react-i18next"」が表示する
 1)エラー内容
 2)インストールされているか確認するには
 3)対応策

【1】reactでの多言語対応

* react-i18next を使う

1)補足:i18n

* i18n(アイエイティーン) = internationalization(国際化
* アプリケーションなどを様々な言語や地域に対応できるように
 設計・開発するプロセス

【2】作業の流れ

1)ライブラリのインストール
2)翻訳ファイル作成
3)i18next の初期設定
4)React コンポーネントでの使用方法

1)ライブラリのインストール

npm install i18next react-i18next i18next-browser-languagedetector
npm install --save-dev @types/i18next @types/react-i18next

2)翻訳ファイル作成

# 以下のようにファイルを配置

src/
 ├─ locales/
 │   ├─ en/
 │   │   └─ translation.json
 │   └─ ja/
 │       └─ translation.json

src/locales/en/translation.json

{
  "hello": "Hello!",
  "welcome": "Welcome to our website"
}

src/locales/ja/translation.json

{
  "hello": "こんにちは!",
  "welcome": "私たちのサイトへようこそ"
}

3)i18next の初期設定

src/i18n.ts

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';

import enTranslation from './locales/en/translation.json';
import jaTranslation from './locales/ja/translation.json';

// Define the resources object with type safety
export const resources = {
  en: { translation: enTranslation },
  ja: { translation: jaTranslation },
} as const;

export const defaultNS = 'translation';

i18n
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    resources,
    lng: 'en',
    fallbackLng: 'en',
    interpolation: { escapeValue: false },
  });

export default i18n;

src/react-i18next.d.ts

// 型補完を有効化
import 'react-i18next';
import type { resources, defaultNS } from './i18n';

declare module 'react-i18next' {
  interface CustomTypeOptions {
    defaultNS: typeof defaultNS;
    resources: typeof resources['en'];
  }
}

src/main.tsx

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './i18n'; // ADD!!
import App from './App.tsx'

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <App />
  </StrictMode>,
)

src/App.tsx

import React from 'react';
import { useTranslation } from 'react-i18next';

function App() {
  const { t, i18n } = useTranslation();

  const handleChangeLanguage = (lang: 'en' | 'ja') => {
    i18n.changeLanguage(lang);
  };

  return (
    <React.Fragment>
      <div style={{ padding: 20 }}>
        <Stack direction="row" spacing={2} sx={{ mt: 3 }}>
          <Button variant="contained" onClick={() => handleChangeLanguage('en')}>
            {t('english')}
          </Button>
          <Button variant="outlined" onClick={() => handleChangeLanguage('ja')}>
            {t('japanese')}
          </Button>
        </Stack>
      </div>
       ...
    </React.Fragment>
  );
}

export default App;

4)React コンポーネントでの使用方法

* 他のコンポーネントで使うのは以下の通り。

src/Xxx.tsx .

import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';

const Xxx: React.FC = () => {
  const { t } = useTranslation(); // ADD!!

  return (
        {t('hello')} // ここで呼び出す
  );
};

export default Xxx;

【3】エラー「Failed to resolve import "react-i18next"」が表示する

1)エラー内容

[vite:import-analysis] Failed to resolve import "react-i18next"
 from "src/App.tsx". Does the file exist?

2)インストールされているか確認するには

# npm ls [ライブラリ]
npm ls i18next react-i18next i18next-browser-languagedetector

frontend@0.0.0 /app
├── i18next@25.6.0
├── i18next-browser-languagedetector@8.2.0
└── react-i18next@16.0.0

3)対応策

[1] キャッシュ削除

rm -rf node_modules/.vite
rm -rf node_modules/.cache

[2] モジュールを再インストール

# npm uninstall @types/react-i18next
npm install

[3] Vite を強制再起動

npm run dev -- --force

関連記事

React ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2020/04/29/000000
React ~ Material UI / 入門編 ~
https://dk521123.hatenablog.com/entry/2025/10/14/224514
Vite 〜 入門編 〜
https://dk521123.hatenablog.com/entry/2025/10/08/004137