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

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

react-i18nextで多言語対応(言語切り替え)をしようと思ったら、エラーが出てできなかった。

動作環境

  • “react”: “16.4.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”

エラー

コンパイル後のブラウザ画面にでたエラー

    TypeError: Object(...) is not a function
    useTranslation
    node_modules/react-i18next/dist/es/useTranslation.js:45
    42 | var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; // assert we have the needed i18nInstance
    43 | 
    44 | var i18nFromProps = props.i18n;
    > 45 | var ReactI18nContext = useContext(I18nContext);
        | ^  46 | 
    47 | var _ref = getHasUsedI18nextProvider() ? ReactI18nContext || {} : {},
    48 |     i18nFromContext = _ref.i18n,

原因

Reactのバーションとreact-i18nextのバージョンが合ってない。

react-i18nextをインストールした時のWARNに注目

npm install --save react-i18nextをした後のWARNを良くみてみると、reactのバージョンが違うと怒られています。

npm WARN react-i18next@10.13.1 requires a peer of react@>= 16.8.0 but none is installed. You must install peer dependencies yourself.

本来は、reactのバージョンを16.8.0以上に変更するのがいいと思いますが、
すでにそこそこの規模のサービスが動いているので、reactのバージョンをあげるのは正直怖い・・・。
今度ちゃんとリファクタリング期間を設けて、バージョンあげるなりしなきゃだと思いますが、
とりあえず今は、react-i18nextの方のバージョンを下げることにしました。

対応

react-i18nextのバージョンを9に変えます。

npm install react-i18next@legacy i18next --save

コードの変更

コードv9のものに変更する必要があります。

v10v9
withTranslationwithNamespaces
initReactI18nextreactI18nextModule

コンパイルしてもエラーが出なくなりました。

最終的な動作環境

  • “react”: “16.4.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”
  • “react-i18next”: “^9.0.10”
  • “i18next”: “^19.0.1”
  • “i18next-browser-languagedetector”: “^4.0.1”

v9のドキュメント

Step by step guide (v9) | react-i18next documentation
Migrating v9 to v10 | react-i18next documentation

reactのバージョンをあげたバージョン

Reactで言語切り替え(多言語対応)
react-i18nextで日本と英語の切り替えをしてみた。 公式のクイックスタートを参考に実装します。 環境 "react": "16.8.0" "redux": "^3.6.0" "react-redux": "^5.0.5" "rea...

コメント

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