i18next + react-i18nを使った国際化 🌎

ただの例ですけど、私のマシンでちゃんと動きました!
多様なユーザーに対応するには、言語の壁がとても重要なので、プロジェクトに何らかの国際化対策があることが大切です。国際化を実装する方法はたくさんありますが、i18next + react-i18nを使うとすごく簡単で早かったです。
やり方:
- プロジェクトを作成する(私はviteを使っています):
npm create vite@latest
- インストールする:i18next + react-i18n
npm install react-i18next i18next --save
libというフォルダを作成し、i18n.tsというファイルを作る: > こんな感じです
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
i18n.use(initReactI18next).init({
resources: {},
lng: "en", // プロジェクトでデフォルトにしたい言語
});
src内にlocaleというフォルダを作り、そこに.jsonファイルを追加します。この例では2つ作りました。en.jsonは英語用で、pt.jsonはポルトガル語用です。en.json
{
"translation":{
"header": "Our Header",
"footer": "Our Footer {{year}}"
}
}
pt.json
{
"translation":{
"header": "Nosso Cabeçalho",
"footer": "Nosso Rodape {{year}}"
}
}
i18n.tsファイルに戻って:
こんな感じです
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
// 翻訳ファイルを追加する
import enTranslations from "../locale/en.json";
import ptTranslations from "../locale/pt.json";
i18n.use(initReactI18next).init({
resources: {
en: { ...enTranslations },
pt: { ...ptTranslations },
},
lng: "en",
});
最後のステップ!
main.tsxファイルに行って、i18n.tsファイルをインポートする:
import "./lib/i18n.ts";
App.tsxに行って使ってみましょう
useTranslationフックを追加する:
const {
t,
i18n: { changeLanguage, language },
} = useTranslation();
- 言語を切り替えるためにuseStateを作る:
const [currentLang, setCurrentLang] = useState(language);
- 言語を切り替えるシンプルな関数を作る:
const switchLang = () => {
const newLang = currentLang === "en" ? "pt" : "en";
changeLanguage(newLang);
setCurrentLang(newLang);
};
- App.tsxを変更して、理論をテストする!
こんな感じです
return (
<>
<h1>{t("header")}</h1>
<button type="button" onClick={switchLang}>
Change Language manually
</button>
<footer>
<h1>{t("footer", { year: new Date().getFullYear() })}</h1>
</footer>
</>
);
- 見ての通り、翻訳を使うには、
.json言語ファイルに作ったトークンをtを通して渡す必要があります。
結果
英語で!

ポルトガル語で!

連絡先:
- Github: https://github.com/guim0
- LinkedIn: https://www.linkedin.com/in/guim0-dev/
こちらの記事はdev.toの良い記事を日本人向けに翻訳しています。
https://dev.to/guim0/internationalization-with-i18next-react-i18n-4m28








