Guide: How to Set Up i18n for Multi-Language Support in React Applications

Guide: How to Set Up i18n for Multi-Language Support in React Applications

1. Create i18n.js File

In your src folder, create a file named i18n.js.

Install Dependencies:

npm install i18next react-i18next i18next-browser-languagedetector i18next-http-backend

Copy and paste the following code:

import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import Backend from "i18next-http-backend";

i18n
  .use(Backend)
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    fallbackLng: "en", // Default fallback language
    debug: false,
    interpolation: {
      escapeValue: false,
    },
    backend: {
      loadPath: "/locales/{{lng}}/translation.json", // Path to translation files
    },
    detection: {
      order: [
        "querystring",
        "cookie",
        "localStorage",
        "navigator",
        "htmlTag",
        "path",
        "subdomain",
      ],
      lookupQuerystring: "lng",
      lookupCookie: "i18next",
      lookupLocalStorage: "i18nextLng",
      caches: ["localStorage", "cookie"],
      excludeCacheFor: ["cimode"],
      checkWhitelist: true,
      lookupFromPathIndex: 0,
      lookupFromSubdomainIndex: 0,
    },
    supportedLngs: ["en", "ar"], // Supported languages
    nonExplicitSupportedLngs: true,
    load: "languageOnly",
  });

export default i18n;

2. Set Up Translation Files

Create a folder structure in the public directory: public/locales/en/translation.json and public/locales/ar/translation.json.

Fill each file with translations:

public/locales/ar/translation.json:

{
  "welcome": "السلام عليكم ورحمة الله وبركاته"
}

public/locales/en/translation.json:

{
  "welcome": "Welcome to our website!"
}

3. Initialize i18n in Your Project

In your main.jsx, import the i18n.js file to initialize it:

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import "./i18n"; // Import i18n configuration

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById("root")
);

4. Implement useTranslation in a Component

In any component, use the useTranslation hook to access translation functionality. Additionally, you can use the fallback or default language text directly in the t() function in case a translation is missing or the key isn't defined.

import React from "react";
import { useTranslation } from "react-i18next";

const App = () => {
  const { t, i18n } = useTranslation();

  const changeLanguage = (lng) => {
    i18n.changeLanguage(lng);
  };

  return (
    <div>
      <p>
        {/* Using fallback text within the `t()` function if the key is missing */}
        {t('welcome', 'Welcome to our website!')} 
      </p>
      <button onClick={() => changeLanguage('en')}>English</button>
      <button onClick={() => changeLanguage('ar')}>Arabic</button>
    </div>
  );
};

export default App;

Explanation of Fallback within the t() Function

In the above example, the fallback or default language text is included directly inside the t() function as the second argument. This is particularly useful if:

  • The translation key is missing: If t('welcome') doesn't find the key in the translation files, it will use 'Welcome to our website!' as the default text.
  • During development: You can include default text to make sure the app doesn't break or display empty content while waiting for translations to be added.

This approach ensures that your components always display meaningful text even if a translation isn't available for the current language.

5. Test Dynamic Language Switching

Run your application and ensure the language switches when clicking the "English" or "Arabic" buttons.

Verify that:

  • Language switching works: Clicking the buttons should switch the language.
  • Fallback works: If a translation is missing, the fallback text provided in the t() function will be displayed.
  • Language setting persists: LocalStorage and cookies should retain the selected language across sessions.

Done!