Reactで言語切り替え(多言語対応)

React
※当ブログの記事内にはプロモーションが含まれている場合があります。

react-i18nextで日本と英語の切り替えをしてみた。
公式のクイックスタートを参考に実装します。

環境

  • “react”: “16.8.0”
  • “redux”: “^3.6.0”
  • “react-redux”: “^5.0.5”
  • “react-dom”: “16.4.0”
  • “webpack”: “4.28.3”
  • “webpack-dev-server”: “3.1.14”
  • “i18next”: “^19.0.1”
  • “react-i18next”: “^11.2.5”
  • “i18next-browser-languagedetector”: “^4.0.1”

i18next インストール

react-i18nextを使うには、i18nextが必要らしいので、一緒にインストールします。

npm install --save i18next react-i18next

 

i18next-browser-languagedetectorもインストールします。
i18next-browser-languageDetectorは、ブラウザで使用されている言語を検出してくれるものらしい。
参考

npm install --save i18next-browser-languagedetector

 

言語設定

下記の例だと、こんにちは!という日本語が設定された時、
英語環境では、Hello!に切り替わるようになる。

src/constants/translations.js


    export default {
        en: {
            translation: {
                'こんにちは!': 'Hello!',
            }
        },
    }

i18nextの設定

src/modules/i18n.js


    import i18n from 'i18next';
    import LanguageDetector from 'i18next-browser-languagedetector';
    import { initReactI18next } from 'react-i18next';
    import resources from '../constants/translations'

    i18n
        .use(LanguageDetector)
        .use(initReactI18next)
        .init({
            resources, // ../constants/translationsを設定する

            lng: 'ja',
            fallbackLng: 'ja',
            debug: true,

            keySeparator: false,

            interpolation: {
                escapeValue: false
            },
        });

    export default i18n;

i18nの設定を適用する

/src/index.jsに追加します。
import './modules/i18n'

言語切り替えをする

方針

言語切り替えを適用させたいファイルで下記をインポートする
import { withTranslation } from 'react-i18next';


    import PropTypes from 'prop-types'
    import React, { Component } from 'react'
    import { connect } from 'react-redux'
    import { browserHistory } from 'react-router'
    import { withTranslation } from 'react-i18next';
    
    class LangSwitch extends Component {
        constructor(props) {
            super(props)
            this.state = {
            }
        }
        
        render() {
            const { t, i18n } = this.props
            return (
                {t('こんにちは!')}
            )
        }
    }
    
    const mapStateToProps = (state) => {
        return {}
    }
      
    const mapDispatchToProps = (dispatch) => {
        return {}
    }
      
    export default connect(mapStateToProps, mapDispatchToProps)(withTranslation()(LangSwitch))

言語の表示を切り替える

インポート

import { withTranslation } from 'react-i18next';

withTranslation追加

export default connect(mapStateToProps, mapDispatchToProps)(withTranslation()(LangSwitch))
これを追加しておくと、t,i18npropsが使えるようになる。

t, i18nを変数に入れておく

const { t, i18n } = this.props

いよいよ使う

{t('こんにちは!')}

React の Higher-order Components の利用方法 - Qiita
前書きこの資料は2016/12/15 に行われた【ランサーズ×Mozilla×freee】React実践!勉強会で発表した際の資料を改修したものです。(qitta に投稿するのが初めての場合、2…
https://react.i18next.com/latest/withtranslation-hoc

ボタンで適用する言語を切り替える

Englishのボタンを押すと、こんにちは!部分がHello!に切り替わるようになり、
日本語のボタンを押すと、こんにちは!に切り替わるようになります。

   <button type="button" onClick={()=>{ i18n.changeLanguage('ja') }}>日本語</button>
    <button type="button" onClick={()=>{ i18n.changeLanguage('en') }}>English</button>

エラーになった場合

TypeError: Object(...) is not a functionというエラーが出てしまった時の対応を別の記事に書きました。

react-i18nextのエラー:TypeError: Object(…) is not a function useTranslation

参考サイト

Internationalization In ReactJS Application Using i18Next
In this article, you will learn about internationalization in ReactJS application using i18Next.
Quick start | react-i18next documentation
https://react.i18next.com/latest/using-with-hooks#install-needed-dependencies
Add or Load Translations | i18next documentation
i18nextを使ってフロントエンドでお手軽ローカライズ - Qiita
ランディングページのようなちょっとした静的ページをローカライズしたい時があると思います。そんな時に便利なi18nextを導入してみて便利だったので共有します。i18nextって?https:/…
react-i18nextで多言語対応(国際化・i18n)を素振り | suzukalight.com
最近ははじめから世界で勝負しようと頑張っているアプリも増えてきています。その場合に、障壁のひとつとなるが多言語対応(国際化・i18n)の方法だと思います。今回はこの i18n について素振りしてみました。 まえがき 完成品 実装したリポジト...
GitHub - i18next/i18next-xhr-backend: [deprecated] can be replaced with i18next-http-backend
can be replaced with i18next-http-backend - i18next/i18next-xhr-backend
Attention Required! | Cloudflare

translations-in-separated-json-files

 

メモ

i18next-xhr-backendは必要

i18next-xhr-backendは必要なのか・・・・?
これは、
リソースのロードに利用
言語毎に文字列を定義したJSONファイルを切り替えることができます。
らしい・・・。
引用元:https://qiita.com/moioyoao/items/d69b9450cbcf58597f71
引用元:https://qiita.com/yun_bow/items/76a5339aebedd343834a

xhrでロードするなら使った方がいいよ、ということらしい・・・・・。

If you like to load them via xhr – yes. There are other options like bundling them or custom backends, the list is endless: https://www.i18next.com/overview/plugins-and-utils Or creating a own implementation: https://www.i18next.com/misc/creating-own-plugins The one misconfiguration i spot in your options is that backend options are nested in resources…those should be on top level plus do not add resources on init if you like to load them.

引用元:https://stackoverflow.com/questions/50791429/do-i-need-i18next-xhr-backend-for-using-translations-in-separated-json-files

xhr: XMLHttpRequest
ブラウザ上でサーバーとHTTP通信を行うためのAPIです。
引用元:https://gihyo.jp/dev/serial/01/crossbrowser-javascript/0012
スキーム、ドメイン、ポートの制限があり、比較的安全に通信できる

コメント

タイトルとURLをコピーしました