To use react-i18next, you will need to pass in an i18next instance by using `initReactI18next`.
This function is used to configure and initialize the i18next library for your React application.
Here is an example of how to set up react-i18next with `initReactI18next`:
import React from 'react';
import { initReactI18next } from 'react-i18next';
import i18n from 'i18next';
// Import your translations
import translationEN from './locales/en/translation.json';
import translationFR from './locales/fr/translation.json';
// Set up i18next instance with translations
i18n
.use(initReactI18next)
.init({
resources: {
en: {
translation: translationEN,
},
fr: {
translation: translationFR,
},
},
lng: 'en', // Default language
fallbackLng: 'en', // Fallback language
interpolation: {
escapeValue: false, // React already escapes values by default
},
});
function App() {
return (
<div>
<h1>{'Hello World!'}
<p>{'Welcome to my app.'}
);
}
export default App;
In this example, we import the `initReactI18next` function from the `react-i18next` package,
along with the `i18n` instance from the `i18next` library. We also import the translation files
for English and French.
We then set up the `i18n` instance using `initReactI18next` as a plugin, and configure it with
the imported translations. We also specify the default language as English and the fallback
language as English. Additionally, we disable value escaping in the interpolation options
since React already does this by default.
Finally, we define our React component `App` and render some sample content within a `div`.
You can now start using `{`t(‘translationKey’)`}` in your components to access the translated phrases,
where `’translationKey’` matches the keys in your translation files.