<aside> 💡 We use react-i18next for this feature.

</aside>

Config step by step

Install:

npm install react-i18next@legacy i18next --save

Add translation file (/public/locales/en/index.json):

{
  "Welcome to React": "Welcome to React and react-i18next"
}

Config I18n (/src/i18n.js)

import i18n from "i18next";
import { reactI18nextModule } from "react-i18next";

import translationEN from '../public/locales/en/translation.json';

// the translations
const resources = {
  en: {
    translation: translationEN
  }
};

i18n
  .use(reactI18nextModule) // passes i18n down to react-i18next
  .init({
    resources,
    lng: "en",

    keySeparator: false, // we do not use keys in form messages.welcome

    interpolation: {
      escapeValue: false // react already safes from xss
    }
  });

export default i18n;

Import to index file (main.js)

import './i18n'
ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
)

Auto detect user language

Install

npm install i18next-browser-languagedetector --save

config i18n (after that you can let user toggle change langue by your function)

import i18n from "i18next";
import detector from "i18next-browser-languagedetector";
import { reactI18nextModule } from "react-i18next";

import translationEN from '../public/locales/en/translation.json';
import translationDE from '../public/locales/de/translation.json';

// the translations
const resources = {
  en: {
    translation: translationEN
  },
  de: {
    translation: translationDE
  }
};

i18n
  .use(detector)
  .use(reactI18nextModule) // passes i18n down to react-i18next
  .init({
    resources,
    fallbackLng: "en", // use en if detected lng is not available

    keySeparator: false, // we do not use keys in form messages.welcome

    interpolation: {
      escapeValue: false // react already safes from xss
    }
  });

export default i18n;

Lazy loading

i18n 
  .use(detector)
  .use(backend)
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    fallbackLng: "en", // use en if detected lng is not available

    keySeparator: false, // we do not use keys in form messages.welcome

    interpolation: {
      escapeValue: false // react already safes from xss
    },
		
    react: {
      wait: true, // lazy loading
      useSuspense: false
    }
  });

Thứ tự khi nạp các file ngôn ngữ sẽ được nạp như sau:

  1. ‘common.json’: file này sẽ được nạp đầu tiên khi user đăng nhập hoặc không.