React i18n Internationalization and Localization Tutorial

Seldom, your site gets popular in the country or region where a generally different language is used then your site being used. For instance, it could be the content of your site, dates, numerical values, etc.

Nowadays, the myth of global boundaries is relinquished., the world has come even closer thanks to globalization.

These days, adding multi-language support in web applications is more than required; it allows your site visitors to consume your site’s content. But, not just that, it also creates the consensus between your software application and the consumer. Which we presume a win-win situation for both parties.

This react localization tutorial’s idea revolves around creating a multi-language react site and adding internalization in react using the npm translation packages.

This guide will show you how to translate dates using the moment package, how to set up the multilingual environment in react. How to create multiple translation files and connect with react reusable component from scratch.

To accomplish the task, we will use some of the sturdy plugins, which are not ordinarily plugins but are a true prodigy.

How to Add Multilingual Support in React using i18n

Let us add internationalization to React app with the help of i18next library.

  • Step 1: Download React Project
  • Step 2: Install Bootstrap Package
  • Step 3: Add Language Translator Packages
  • Step 4: Add Moment Package
  • Step 5: Create Locale Files
  • Step 6: Add i18n Translation Settings
  • Step 7: Create Multi-language Component
  • Step 8: Add Language Switching Buttons
  • Step 9: Start React Application

Download React Project

The node js and npm are compulsory to get along with this tutorial, and we assume you have already installed it.

Let’s hit the road; Installing react app is super easy; just execute the suggested command.

npx create-react-app react-multilingual-app

Now, you have to take a baby step to get inside the app.

cd react-multilingual-app

Install Bootstrap Package

Designing component with HTML and CSS is easy but take ample amount of time. To lower down the frontend design time, we may use the bootstrap package; it helps to build UI components swiftly.

npm install bootstrap

Add Language Translator Packages

This section shares some of the commands that allow adding i18next, react-i18next, and i18next-browser-languagedetector packages.

npm install i18next i18next-browser-languagedetector react-i18next

i18next: It is a notable internationalization framework for browser or any other javascript environment.

i18next-browser-languagedetector: i18next language detection plugin use to detect user language in the browser.

react-i18next: A powerful internationalization framework for React and React Native which is based on i18next.

Add Moment Package

To correctly implement date/time and number translations in react expects to use moment.js, it is available through the npm moment package.

The moment is a JavaScript date library for relentlessly parsing, validating, manipulating, and formatting dates.

npm install moment

Create Locale Files

Next, you have to create a locales folder in the src directory.

Further, create src/locales/en folder also create translatons.js file within.

Update the src/locales/en/translatons.js file with data to be translated in another language.

export const ENGLISH = {
    blog:  {
        "featured": "Featured",
        "title": "React Reusable Modal Dialog",
        "description": "Build responsive modal dialog component example",
        "publish": "{{date, DD-MM-YYYY}}"
    }
};

Moreover, create src/locales/fn folder also create translatons.js file within.

Add the code in src/locales/fn/translatons.js file with another language code.

export const FRENCH = {
    blog:  {
        "featured": "Mis en exergue",
        "title": "Boîte de dialogue modale réutilisable React",
        "description": "Créer un exemple de composant de dialogue modal réactif",
        "publish": "{{date, DD-MM-YYYY}}"
    }
};

Add i18n Translation Settings

We have created the translation files for English and French languages. Next, create an i18n.js file inside the locales folder, then place the below code in the src/locales/i18n.js file.

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

import { ENGLISH } from "./en/translatons";
import { FRENCH } from "./fn/translatons";

i18n
 .use(LanguageDetector)
 .use(initReactI18next)
 .init({
   resources: {
     en: {
       translation: ENGLISH
     },
     fn: {
       translation: FRENCH
     }
   },
   interpolation: {
    format: function (value, format, lng) {
      if (value instanceof Date) 
      return moment(value).format(format);
      return value;
    }
  }
 });
 
i18n.changeLanguage("fn");

Import locales file, process the translation files using i18n, at the same time moment is helping us here to translate date and time in react.

Create Multi-language Component

Next, move to the src directory, create components folder and inside this folder create user.component.js file. Afterward, add the following code in the components/user.component.js file.

import React from "react";
import { useTranslation } from "react-i18next";
import "../locales/i18n";
 
export const UserComponent = () => {

 const { t } = useTranslation();
 
 return (
   <div>
        <div className="card text-center">
            <div className="card-header">
                {t("blog.featured")}
            </div>
            <div className="card-body">
                <p>{t("blog.title")}</p>
                <p>{t("blog.description")}</p>
            </div>
            <div className="card-footer text-muted">
                <p>{t('blog.publish', { date: new Date() })}</p>
            </div>
        </div>
   </div>
 );
};

Use the useTranslation package to translate website content in the desired language, plus show the translated date/time in the react view.

Add Language Switching Buttons

So, In the end, we need to define the buttons with the onChange event handler; buttons will switch the locales based on the user’s choice. Ideally, we have to import the user component and add the lang property to it.

Eventually, open the src/App.js file and update the code.

import React, { useState } from "react";
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import './App.css';
import { UserComponent } from "./components/user.component";
import i18n from "i18next";

 
export default function App() {
 
  const [language, setLanguage] = useState('en');
  
  const onLangChange=(event)=>{
    event.preventDefault();
    setLanguage(event.target.value);
    i18n.changeLanguage(event.target.value);
  }

   return (
    <div className="App container mt-5">
      <div className="mb-3">
          <button value='en' onClick={onLangChange}>English</button>
          <button value='fn' onClick={onLangChange}>French</button>
      </div>

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

Start React Application

In order to test the application, you must start the react development server. Don’t be skeptical; run the provided command.

When the server starts; immediately after you see the imprinted urls on the terminal window; you may use the url to test the app on the browser.

npm start

Conclusion

React internationalization and localization example are over; So in this tutorial, we comprehend how to add an internationalization feature in React app simply. Plus, we learned the easy way to use the i18next adapter in react and refrain ourselves from moving heaven and earth. Additionally, we showed you how to convert content, dates from one language to another language, especially we examined moment js’ working and integration procedure with i18next library.

The resonance of every magical step we explained in this guide will definitely explicate the subtle as well as pragmatic paths required for building react internationalization example.

We hope you will shower your love on this tutorial, “All the good things come to an end” In the same way, the time has come to say goodbye. , so good day to you.