Using the i18next hook
HOCs are confusing. Containers are ugly. Hooks to the rescue.
Internationalization must be one of the first few basic facilities you add into your app. I looked at i18next and react-intl. One had hooks and the other didn’t. Judging buy the commits, it looks like no one even cares about react-intl anymore. The choice was simple.
There are two steps to setting this up:
- Initialize i18next
- Use the hook
Initialize i18Next
// file i18n.jsimport i18n from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from "i18next-browser-languagedetector";i18n
.use(LanguageDetector)
.use(initReactI18next)
.init({
resources: {
en: {
translation: {
"Hello World": "Hello i10n Next Hook",
Magic: "Start the Magic"
},
},
});
It is a blob of code, I know. Definitely not copy/paste worthy. But I’ll give you a link to a much better organized project in a bit.
Use the hook
// file index.jsimport { useTranslation } from "react-i18next";
import "./i18n"; function App() {
const { t } = useTranslation();
return (
<div className="App">
<h1>{t("Hello World")}</h1>
<h2>{t("Magic")}</h2>
</div>
);
}
No boilerplate code. Any where you need the translations, just use the hook. All the magic behind it is abstracted away.
Here is the link to a working code sandbox. https://codesandbox.io/s/vjxn4qmm9l