To get current language with react-i18next, we can inject the i18n
prop into our component with the withTranslation
higher order component.
For instance, we write:
import React from "react";
import i18n from "i18next";
import { withTranslation, initReactI18next } from "react-i18next";
i18n.use(initReactI18next).init({
resources: {
en: {
translation: {
"Welcome to React": "Welcome to React and react-i18next"
}
}
},
lng: "en",
fallbackLng: "en",
interpolation: {
escapeValue: false
}
});
const HomeComponent = ({ i18n }) => {
return <div>{i18n.language}</div>;
};
const Home = withTranslation()(HomeComponent);
export default function App() {
return (
<div>
<Home />
</div>
);
}
We initialize react-i18next with:
i18n.use(initReactI18next).init({
resources: {
en: {
translation: {
"Welcome to React": "Welcome to React and react-i18next"
}
}
},
lng: "en",
fallbackLng: "en",
interpolation: {
escapeValue: false
}
});
Next, we create the HomeComponent
that takes the i18n
prop.
And we get the current language with the i18n.language
property.
Next, we call the withTranslation
HOC with HomeComponent
to return a new component with the i18n
prop set.
Finally, we render Home
in App
.