npm install react-i18next i18next i18next-browser-languagedetector --save
yarn react-i18next i18next i18next-browser-languagedetector --saveimport i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import translationEn from './translation.json';
import translationEs from './translation.json';
const fallbackLng = ['en'];
const availableLanguages = ['en', 'es'];
const resources = {
en: {
translation: translationEn,
},
es: {
translation: translationEs,
},
};
i18n
.use(LanguageDetector)
.use(initReactI18next)
.init({
resources,
fallbackLng,
detection: {
checkWhitelist: true,
},
debug: false,
react: {
useSuspense: false,
},
whitelist: availableLanguages,
interpolation: {
escapeValue: false,
},
});
export default i18n;Start i18next in the app index.
import React from 'react';
import ReactDOM from 'react-dom/client';
import "./i18nextInit";
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);There must be a translation file for each language with the same keys.
We will use these files in the resources of the i18next configuration as shown in the file above.
{
"greeting": "Hola mundo",
}{
"greeting": "Hello world",
}import { useTranslation } from 'react-i18next';
const App = () => {
const { t } = useTranslation();
return (
<h1>{t('greeting')}</h1>
)
}i18next.changeLanguage(language);