Clue Mediator

Implement multi-languages in React

📅January 17, 2021

Today, we will show you how to implement multi-languages in React. Sometimes you may need to add multi-language support to a website or a react web application like English, Chinese, etc.

In this article, we’ll use the react-i18next internationalization framework for React App which is based on i18next.

Demo Application

We will create a multilingual sample application as shown below.

Output - Implement multi-languages in React - Clue Mediator

Output - Implement multi-languages in React - Clue Mediator

Steps to implement multi-languages in React

  1. Create a react app
  2. Install dependencies
  3. Add translation files
  4. Configure the i18next
  5. Initialize the i18next configuration
  6. Translate component using react-i18next
  7. Output

File Structure

  • react-multi-lingual

    • node_modules

    • public

      • assets

        • i18n

          • translations

            • en.json
            • zh-Hant.json
    • src

      • components

        • HelloWorld.js
        • LangSelector.js
        • ReactExample.js
        • ThankYou.js
      • App.js

      • i18n.js

      • index.css

      • index.js

    • package-lock.json

    • package.json

1. Create a react app

First of all, we will create a simple react application using the `create-react-app` npm package. Run the following command to create a react app.

npx create-react-app react-multi-lingual

Check the following link for more information.

Create a react application

2. Install dependencies

To integrate multi-languages in the react app, we have to install the react-i18next packages. Run the following command to install the dependencies.

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

3. Add translation files

Now, we have to add the following translation files in the public/assets/i18n/translations/ folder. You have to create directories for the translation files.

en.json

{
  "HELLO_WORLD": "Hello World!",
  "REACT_EXAMPLE": "This is a react example ({{count}}).",
  "THANK_YOU": "Thank you!"
}

zh-Hant.json

{
  "HELLO_WORLD": "你好,世界!",
  "REACT_EXAMPLE": "這是一個反應示例({{count}})。",
  "THANK_YOU": "謝謝!"
}

4. Configure the i18next

In this step, we will create the `i18next` initiation script. Let’s create a file named `i18n.js` under the src/ directory.

i18n.js

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

import Backend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';

i18n
  // load translation using http -> see /public/locales (i.e. https://github.com/i18next/react-i18next/tree/master/example/react/public/locales)
  // learn more: https://github.com/i18next/i18next-http-backend
  .use(Backend)
  // detect user language
  // learn more: https://github.com/i18next/i18next-browser-languageDetector
  .use(LanguageDetector)
  // pass the i18n instance to react-i18next.
  .use(initReactI18next)
  // init i18next
  // for all options read: https://www.i18next.com/overview/configuration-options
  .init({
    lng: 'en',
    backend: {
      /* translation file path */
      loadPath: '/assets/i18n/{{ns}}/{{lng}}.json'
    },
    fallbackLng: 'en',
    debug: true,
    /* can have multiple namespace, in case you want to divide a huge translation into smaller pieces and load them on demand */
    ns: ['translations'],
    defaultNS: 'translations',
    keySeparator: false,
    interpolation: {
      escapeValue: false,
      formatSeparator: ','
    },
    react: {
      wait: true
    }
  });

export default i18n;

5. Initialize the i18next configuration

In this step, we will import the `i18n.js` in the `Index.js` file to initialize the i18next configuration. Here, we have to use the suspense component because `i18next` load resource files asynchronously and we have to wait until the loading is completed.

Index.js

import React, { Suspense } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

import './i18n';

ReactDOM.render(
  <react class="strictmode">
    <suspense fallback="{<span">Loading...}>
      <app>
    </app></suspense>
  </react>,
  document.getElementById('root')
);

6. Translate component using react-i18next

Let’s create three components for the demonstration under src/components/ directory.

  • HelloWorld.js - Translate the component using the hooks.
  • ThankYou.js - Use the HOC to translate the component.
  • ReactExample.js - Use the Trans component to translate the complex react component.

We will also create a `LangSelector.js` component to manage the language selection for the react application.

LangSelector.js

import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';

const LangSelector = () => {
  const { i18n } = useTranslation();
  const [selectedLang, setSelectedLang] = useState('en');

  const changeLanguage = (event) => {
    setSelectedLang(event.target.value);
    i18n.changeLanguage(event.target.value);
  }

  return (
    <div onchange={changeLanguage}>
      <label class="mr10"><input type="radio" value="en" name="language" checked =="=" 'en'}=""> English</label>
      <label><input type="radio" value="zh-Hant" name="language" checked =="=" 'zh-hant'}=""> Chinese (Traditional)</label>
    </div>
  )
}

export default LangSelector;

HelloWorld.js

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

const HelloWorld = () => {
  const { t } = useTranslation();

  return (
    <div>
      <b>{t('HELLO_WORLD')}</b>
    </div>
  )
}

export default HelloWorld;

ThankYou.js

import React from 'react';
import { withTranslation } from 'react-i18next';

const ThankYou = ({ t }) => {
  return (
    <div class="tks">
      <i>{t('THANK_YOU')}</i>
    </div>
  )
}

export default withTranslation()(ThankYou);

ReactExample.js

import React from 'react';
import { Trans, withTranslation } from 'react-i18next';

const ReactExample = () => {
  return (
    <div>
      <trans count="3">REACT_EXAMPLE</trans>
    </div>
  )
}

export default withTranslation()(ReactExample);

App.js

import React from 'react'
import HelloWorld from './components/HelloWorld';
import LangSelector from './components/LangSelector';
import ReactExample from './components/ReactExample';
import ThankYou from './components/ThankYou';

function App() {
  return (
    <react class="fragment">
      <h3>Implement multi-languages in React - <a href="https://www.cluemediator.com" target="_blank" rel="noopener noreferrer">Clue Mediator</a></h3>
      <langselector>
      <div class="app">
        <helloworld>
        <reactexample>
        <thankyou>
      </thankyou></reactexample></helloworld></div>
    </langselector></react>
  );
}

export default App;

7. Output

Run the react application and check the output in the browser.

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂

Demo & Source Code

Github Repository StackBlitz Project