DEV Community

Cover image for Multi language in react i18next (easy example)
Adnan al-emran ontor
Adnan al-emran ontor

Posted on

Multi language in react i18next (easy example)

Step 1: Install Required Dependencies

First, install the required packages:


npm install react-i18next i18next i18next-http-backend

Enter fullscreen mode Exit fullscreen mode

This will install react-i18next for React integration, i18next for managing translations, and i18next-http-backend to load JSON translation files from the server.

Step 2: Set Up Translation Files

Create translation JSON files for each language in the public folder of your React project.

For example:


/public
  /locales
    /en
      home.json
      about.json
    /bn
      home.json
      about.json
    /th
      home.json
      about.json

Enter fullscreen mode Exit fullscreen mode

Each language folder contains JSON files for each page (home, about, etc.). You can add more languages or pages as needed.

Example of /locales/en/home.json:


{
  "welcome": "Welcome to our website",
  "slogan": "CONNECT, SHARE, GROW - ALL IN ONE TAP"
}

Enter fullscreen mode Exit fullscreen mode

Example of /locales/en/about.json:


{
  "aboutTitle": "About Us",
  "aboutDescription": "We are a company dedicated to growth and innovation."
}

Enter fullscreen mode Exit fullscreen mode

Similarly, add the corresponding files for other languages (bn, th, etc.).

Step 3: Initialize i18n

Create an i18n.js file to configure i18next with the backend loader and set up the languages and namespaces.

/src/i18n.js:


import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import HttpBackend from "i18next-http-backend";

i18n
  .use(HttpBackend) // Enables loading JSON files
  .use(initReactI18next) // Initializes react-i18next
  .init({
    fallbackLng: "en", // Default language if not set
    backend: {
      loadPath: "/locales/{{lng}}/{{ns}}.json", // Load path pattern for the JSON files
    },
    ns: ["home", "about"], // Define namespaces for each page
    defaultNS: "home", // Default namespace
    interpolation: {
      escapeValue: false, // Disable escaping for simplicity
    },
  });

export default i18n;

Enter fullscreen mode Exit fullscreen mode
  • loadPath specifies where to fetch the translation files.
  • ns defines the namespaces, which are the translation files like home.json, about.json, etc.
  • defaultNS is the default namespace used for missing keys.

Step 4: Load Translations in Components

Use the useTranslation hook to load translations in different components.

Example of Header.js Component:


import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
import { useEffect } from 'react';

const Header = () => {
    const { t, i18n } = useTranslation('home'); // Use 'home' namespace

    const changeLanguage = (e) => {
        const selectedLanguage = e.target.value;
        i18n.changeLanguage(selectedLanguage)
            .then(() => localStorage.setItem('language', selectedLanguage)) // Store selected language in localStorage
            .catch(err => console.error("Language change error:", err));
    };

    useEffect(() => {
        const savedLanguage = localStorage.getItem('language') || 'en'; // Load saved language
        i18n.changeLanguage(savedLanguage)
            .catch(err => console.error("Language load error:", err));
    }, [i18n]);

    return (
        <div>
            <div className="navbar container mx-auto">
                <div className="navbar-start">
                    <Link to="/">
                        <div className="font-queensides text-3xl text-primary font-bold">
                            Card<span className='text-5xl text-secondary'>X.</span>
                            <br />
                            <p className='relative bottom-3 text-[8px]'>
                                {t('slogan')} {/* Use translation key */}
                            </p>
                        </div>
                    </Link>
                </div>

                <div className="navbar-end flex gap-8 font-poppins">
                    <select
                        onChange={changeLanguage}
                        value={i18n.language}
                        className="p-1 border rounded-md bg-white shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                    >
                        <option value="en">🇺🇸 English</option>
                        <option value="bn">🇧🇩 বাংলা</option>
                        <option value="th">🇹🇭 Thai</option>
                    </select>

                    <Link to="#" className="text-sm text-black whitespace-nowrap">{t('contactUs')}</Link>
                </div>
            </div>
        </div>
    );
};

export default Header;

Enter fullscreen mode Exit fullscreen mode
  • useTranslation('home') loads the home.json file. For the "about" page, you would use useTranslation('about').

Step 5: Use Translations in Other Pages

Similarly, use the useTranslation hook in other components and pages.

Example of About.js Component:


import { useTranslation } from 'react-i18next';

const About = () => {
    const { t } = useTranslation('about'); // Use 'about' namespace

    return (
        <div>
            <h1>{t('aboutTitle')}</h1>
            <p>{t('aboutDescription')}</p>
        </div>
    );
};

export default About;

Enter fullscreen mode Exit fullscreen mode

Step 6: Update App.js or Routes

Ensure that your routes are set up properly to render different components and load translations based on the selected language.


import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Header from './Header';
import About from './About';

function App() {
    return (
        <Router>
            <Header />
            <Routes>
                <Route path="/" element={<Home />} />
                <Route path="/about" element={<About />} />
            </Routes>
        </Router>
    );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Step 7: Test the Language Switch

Now, you should be able to switch languages using the dropdown in the Header, and the translations should be updated accordingly across your pages.

Final Directory Structure


/src
  /components
    Header.js
    About.js
  i18n.js
/App.js

/public
  /locales
    /en
      home.json
      about.json
    /bn
      home.json
      about.json
    /th
      home.json
      about.json

Enter fullscreen mode Exit fullscreen mode

Conclusion

  • Namespaces are used to organize translations per page or component (e.g., home.json, about.json).
  • The useTranslation hook loads translations based on the current namespace.
  • The i18next-http-backend plugin loads JSON files from the server.
  • LocalStorage helps persist the selected language across sessions.

Top comments (0)