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