Make your App Multi-lingual with React i18n Internationalization

Internationalization (i18n) is the process of building applications with local languages and cultural settings. An internationalized product solves the need of the local market with a more appropriate language approach and settings which in terms will produce greater user satisfaction and market success.

Happy young people saying hello in different languages. students with speech bubbles and hands in greeting gesture. Free Vector

i18n is usually misrepresented as Localization (L10n) and typically even Translation. i18n is development centered so within the case of software package, one code base is created capable of supporting worldwide languages and locale-specific data formatting and behaviors. It’s a vital and typically underestimated step that’s required for in and scalable L10n.

Tasks involved in i18n Conversion

  • Removal of Hard-coded strings across the application
  • Unicode Compliance
  • Data support for collation
  • Developing application as independant one from specific languages
  • Market and language specific issues to be addressed if required.

Advantages of i18n Conversion

  • High quality source code management.
  • Optimized customer acceptance and delivery.
  • Low effort , cost and time for localization.
  • Better management of multi-lingual applications.
  • Highly agile which makes it easier to maintain and update.

Using i18n Next for React.js

I18n Next is an internationalization javascript framework that provides integration for React.js, Angular Js, and Vue.js. I18n Next is easy to use and highly recommended by developers.

Prerequisites
  • Node.js ( v14+)
  • Npm ( V6.14+)
  • Experience with HTML , Javascript and React.js

Implementation

Step 1:

Create a new React project with the following command and set the current working directory as react-i18n-demo.

npx create-react-app react-i18n-demo
cd react-i18n-demo

Step 2:

Install the dependencies for our application using npm or yarn.

//npm
npm install i18next react-i18next i18next-browser-languagedetector

//yarn
yarn add i18next react-i18next i18next-browser-languagedetector

i18next-browser-languagedetector is used to detect user browser language.

Your package.json will be like this after installation

{
  "name": "react-i18n-demo",
  "version": "1.0.0",
  "description": "React Internationlization Demo",
  "keywords": [
    "react",
    "i18n"
  ],
  "main": "src/index.js",
  "dependencies": {
    "i18next": "19.8.4",
    "i18next-browser-languagedetector": "6.0.1",
    "i18next-icu": "1.4.2",
    "moment": "^2.29.1",
    "react": "17.0.0",
    "react-dom": "17.0.0",
    "react-i18next": "11.7.3",
    "react-scripts": "3.4.3"
  },
  "devDependencies": {
    "i18next-parser": "^3.5.0",
    "typescript": "3.8.3"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "extract-translations": "i18next --fail-on-warnings"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}

Step 3:

Now, let’s create a folder structure for the project like this

The translation folder contains multiple folders for each language with a JSON file. Create the i18n.js file in the translations folder root

// File: i18n.js

import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import moment from "moment";

import TRANSLATIONS_ES from "./es/translation.json";
import TRANSLATIONS_HINDI from "./hindi/translation.json";
import TRANSLATIONS_ZH from "./zh/translation.json";
import TRANSLATIONS_EN from "./en/translation.json";

i18n
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    returnEmptyString: false,
    resources: {
      es: {
        translation: TRANSLATIONS_ES
      },
      hindi: {
        translation: TRANSLATIONS_HINDI
      },
      en: {
        translation: TRANSLATIONS_EN
      },
      zh: {
        translation: TRANSLATIONS_ZH
      }
    }
  });

i18n.init({
  interpolation: {
    format: function (value, format, lng) {
      if (value instanceof Date) return moment(value).format(format);
      if (typeof value === "number")
        return new Intl.NumberFormat().format(value);
      return value;
    }
  }
});

export { i18n };


Each language file created in the translations folder should be imported in React. Each language added in the translations folder should be added in the resources object in the i18n init function().

LANGUAGE_NAME : {
        translation: IMPORTED_LANGUAGE
      }

Step 4:

Lets, add some sample translations in en/translation.json and hindi/translation.json

{
  "welcome": "Welcome",
  "date_format_one": "{{date, YYYY-MM-DD}}",
  "keyWithCount": "is the date where we bought {{count}} Laptops",
  "date_format_two": "{{date, DD-MM-YYYY}}",
  "number_format": "There are {{number, ','}} countries in the world."
}

hindi/translation.json

{
  "welcome": "स्वागत हे",
  "date_format_one": "{{-date, YYYY/MM/DD}}",
  "keyWithCount": "वह तारीख है जब हमने {{count}} लैपटॉप खरीदे ",
  "number_format": "दुनिया में {{number, ','}} देश हैं।"
}

Step 5:

Now, it’s time to implement i18next inside Component.

  1. import useTranslation from react-i18next
  2. import transaltion config file
  3. Use the t() function in i18next.

Let’s create a sample Component with i18n implementation

import React from "react";
import { useTranslation } from "react-i18next";
import "./translations/i18n";

export const ExampleComponent = (props) => {
  const { t } = useTranslation();
  let lng = props.lang;
  return (
    <div>
      <div>
        <p>
          <p>{t("welcome")}</p>
          <p>
            {t("date_format_one", { date: new Date() })} ={" "}
            {t("keyWithCount", { count: 3 })}
          </p>
          <p>{t("number_format", { number: 195 })}</p>
        </p>
      </div>
    </div>
  );
};

In the above example, we need to pass the language as props to the Component. Now, we are going to import the ExampleComponent in the top-level component and pass the language selected in the select box as lang={language}

import React, { useState } from "react";
import { ExampleComponent } from "./ExampleComponent";
import "./styles.css";
import { i18n } from "./translations/i18n";

export default function App() {
  const [language, setLanguage] = useState("en");

  const handleOnclick = (e) => {
    e.preventDefault();
    setLanguage(e.target.value);
    i18n.changeLanguage(e.target.value);
  };

  return (
    <div className="App">

      <select   onChange={handleOnclick}>
        <option selected value="en">English</option>
        <option value="hindi">Hindi</option>
        <option value="es">Spanish</option>
        <option value="zh">Chinese</option>
      </select>

      <ExampleComponent lang={language} />
    </div>
  );
}


i18n.changeLanguage(“en”) is used to change the language using inbuilt function of i18n.

Step 6:

Now, it’s time to execute the application

npm start

You will get output like this as follows

The project Source Code is available here.

Happy Coding!

Leave a comment

Your email address will not be published. Required fields are marked *