React I18n Kit
Edit page
IntroductionInstallationFunctionsFallback (Missing Data)
Higher Order Component
Hook

Dynamic Approach (hook)

If you wrap a component with the withI18n function, 2 properties get exposed. The i18n property that holds the text data and the translate function. The second property is a function that takes one argument, the language in the ISO 639-1 format.

Lets say, you want your default application to be in en, and let the user choose if they want to switch to another language, than you can change the language based on a user event (e.g. click on a button).

Create the translations for your application.

// './i18n/index.js'
const data = {
de: {
text: "Hallo Welt!",
},
en: {
text: "Hello World!",
},
es: {
text: "!Hola Mundo!",
},
};
export { data };

Import your data and the withI18n function from react-i18n-kit and you are ready to go.

import React from "react";
import { useI18n } from "react-i18n-kit";
import { data } from "./i18n";
const DynamicText = () => {
const { i18n, translate } = useI18n(data, { lang: 'en' });
return (
<>
<button onClick={() => translate("en")}>
English
</button>
<button onClick={() => translate("es")}>
Español
</button>
<button onClick={() => translate("de")}>
Deutsch
</button>
<div>{i18n.text}</div>
</>
);
};
export { DynamicText };

Take a look at the output.

Hello World!