2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

i18next で React アプリを日英二言語対応にした実装メモ

2
Posted at

はじめに

個人開発のFXトレード管理アプリを海外ユーザーにも使ってもらうため、
i18next を使って日英二言語対応を実装しました。

セットアップ

npm install i18next react-i18next i18next-browser-languagedetector
// src/i18n/index.js
import i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
import LanguageDetector from 'i18next-browser-languagedetector'

import jaTranslations from './locales/ja'
import enTranslations from './locales/en'

i18n
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    resources: {
      ja: { translation: jaTranslations },
      en: { translation: enTranslations },
    },
    fallbackLng: 'ja',
    interpolation: { escapeValue: false },
  })

export default i18n

翻訳ファイルの構造

// src/i18n/locales/ja/index.js
export default {
  dashboard: {
    title: "ダッシュボード",
    totalProfit: "合計損益",
    winRate: "勝率",
    profitFactor: "プロフィットファクター",
  },
  account: {
    addAccount: "口座を追加",
    noAccounts: "口座が登録されていません",
  },
}

コンポーネントでの使用

import { useTranslation } from 'react-i18next'

function Dashboard() {
  const { t, i18n } = useTranslation()

  return (
    <div>
      <h1>{t('dashboard.title')}</h1>
      <p>{t('dashboard.totalProfit')}: {profit.toLocaleString(i18n.language)}</p>
    </div>
  )
}

言語切替ボタン

function LanguageToggle() {
  const { i18n } = useTranslation()
  const toggle = () => i18n.changeLanguage(i18n.language === 'ja' ? 'en' : 'ja')
  return (
    <button onClick={toggle}>
      {i18n.language === 'ja' ? '🇺🇸 EN' : '🇯🇵 JP'}
    </button>
  )
}

数値・通貨フォーマットの言語対応

// src/i18n/format.js
export function formatCurrency(value, lang) {
  return new Intl.NumberFormat(lang === 'ja' ? 'ja-JP' : 'en-US', {
    style: 'currency',
    currency: lang === 'ja' ? 'JPY' : 'USD',
    minimumFractionDigits: lang === 'ja' ? 0 : 2,
  }).format(value)
}

まとめ

i18next の LanguageDetector を使えばブラウザの言語設定を自動検出して切り替わります。
翻訳ファイルを分離しておくことで、後から言語を追加しやすい構造になります。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?