Going Multilingual with Reacti18next

Last Updated at : March 1, 2019 By - Mohammad Shahzad | 541

    Introduction

    Internationalization become a core part of web applications these days. To expand the business across the globe your application needs some specific changes. There are many ways to handle localization in an application but today we will have to look at how to handle it on frontend using ReactJS,i18next.
    Modern SPAs (single page application) handle localization in very optimal way by translating all your content without any page refresh. we will go step by step showing how to implement localization in a new React application.

    • Step # 01

    You can skip this step if you have already a fresh copy of running React application. Create React App is always a good starting point for any React application. Create a directory and in terminal goto that location. write following command.

    npx create-react-app

    This will create a fresh copy of React application inside the directory.

    • Step # 02

    Now you need to install few npm packages into your project.

    npm i i18next i18next-browser-languagedetector react-i18next

    so now you are done with installation. It’s time to start with configuration.

    • Step # 03

    Now it’s time to create translation files. For the current application i want to support English and Spanish languages. so i need to create two JSON files where all the translation will be kept and imported into the application.
    so the directory structure in src should look something like this.

    [Your Application Name]/src/locales/en/translation.json
    [Your Application Name]/src/locales/es/translation.json

    In translation.json file should be your language tags and its translations. for example in case of locales/en/translation.json the file should look something like this.

    {
    "title": "I am title",
    "text": "I am some demo text"
    }

    while for locales/es/translation.json it should be translation of english version.

    {
    "title": "Soy titulo",
    "text": "Soy un texto de demostración"
    }

    Now that you have translation files its time to configure i18next instance. For that you need to create a file in /src directory with name i18n.js. The file should look something like this.

    import i18n from 'i18next';
    
    import { initReactI18next } from "react-i18next";
    
    //Translations Import
    
    import translationEN from './locales/en/translation.json'
    
    import translationES from './locales/es/translation.json'
    
    i18n
    
      .use(initReactI18next)
    
      .init({
    
        resources: {
    
          en: {
    
            translation: translationEN
    
          },
    
          es : {
    
            translation: translationES
    
          }
    
        },
    
        lng: "en",
    
        fallbackLng: "en",
    
        interpolation: {
    
          escapeValue: false
    
        }
    
      })
    
    export default i18n;

    we are initiating i18n in our application. Also we are importing the translations we created earlier into the file. You can always goto documentation for detailed explanation.
    So now you have successfully integrated i18next into your application. Now it’s time to use it in our components and let it shine.

    • Step # 04

    React i18next offers different types of approaches to translate your content depending on what type of application and design pattern are you following. Personally i like their userTranslation (hook) and withTranslation (HOC) approach. But still its better to read official documentation before jumping to use. For this application i will use these two methods.

    Create React App creates App.js as a starting point for the application and thats where we will be using react i18n. In App.js import the following

    import {withTranslation} from "react-i18next";
    import i18n from "./i18n";

    For demo purpose i will create a title which will be translated into Spanish from english when the user clicks button. For the first method i am using HOC method.

    class App extends Component {
    
      constructor(props){
    
        super(props)
    
        this.state = {
    
          selectedLang : 'en'
    
        }
    
        this.changeLanguageHandler = this.changeLanguageHandler.bind(this)
    
      }
    
      changeLanguageHandler(lang) {
    
        this.setState({
    
          selectedLang : lang
    
        })
    
        i18n.changeLanguage(lang)
    
      }
    
      render() {
    
        const { t } = this.props
    
        return (
    
          <div>
    
            <h2>{t('title')}</h2>
    
            <button onClick={()=>this.changeLanguageHandler(this.state.selectedLang==='en'?'es':'en')}>
    
              Translate to {this.state.selectedLang==='en'?"Spanish":"English"}
    
            </button>
    
          </div>
    
        );
    
      }
    
    }
    
    export default withTranslation()(App);

    Here we have created Change language handler function which simply takes lang tag as an input and set the state of selected lang and trigger changeLanguage method from i18n instance.
    while in template we have receive t function from props using withTranslation HOC. Using t function takes the tag as an input and search for translation in the translations.json that we create for specific language.

    Using userTranslation (Hook) method is very efficient way to have translation in your functional components.

    import React,{useState} from 'react'
    
    import {useTranslation} from "react-i18next";
    
    import i18n from "./i18n";
    
    function App() {
    
      const { t } = useTranslation();
    
      const [selectedLang, setLang] = useState('en');
    
      const changeLanguageHandler = lng => {
    
        setLang(lng)
    
        i18n.changeLanguage(lng);
    
      };
    
      return (
    
        <div>
    
          <span>{t('title')}</span>
    
          <button onClick={()=>changeLanguageHandler(selectedLang ==='en'?'es':'en')}>
    
            Translate to {selectedLang==='en'?"Spanish":"English"}
    
          </button>
    
        </div>
    
      );
    
    }
    
    export default App

    we are importing t function from useTranslation and setting the selected language using useState hook.
    VOILA you have created your react application with multilingual support.

    image courtesy (i18next.com)

    blog user
    Mohammad Shahzad

    Frontend Developer || Tech Enthusiast || Programmer || Photographer || Designer

    Related Posts

    No Related Posts Found