Member-only story
react-i18next NPM Package — withTranslation
3 min readJan 9, 2021
If we want to add localization to a React app, we can use the react-i18next NPM package to do it.
In this article, we’ll look at how to load translations with the withTranslation
higher-order component.
withTranslation
The withTranslation
higher-order component lets us wrap our component to let us gain access to the t
function and i18n
object.
For example, we can write:
import React from "react";
import i18n from "i18next";
import { initReactI18next, withTranslation } from "react-i18next";const resources = {
en: {
ns1: {
"Welcome to React": "Welcome to React and react-i18next"
}
}
};i18n.use(initReactI18next).init({
resources,
lng: "en",
keySeparator: false,
interpolation: {
escapeValue: false
}
});function App({ t }) {
return (
<div className="App">
<p>{t("Welcome to React")}</p>
</div>
);
}export default withTranslation("ns1")(App);
We called the withTranslation
higher-order component with the namespace to load the ns1
translation namespace.
Also, we can load multiple namespaces with it.