How to add multiple language support in ReactJS with i18next and react-i18next?

ReactJS based front-end applications became a standard for web developments. The backend can be written using Java, Node, or Python but in the front-end, ReactJS became an ultimate choice.

When we consider making an international application the first thing it comes in our requirement is the support for multiple languages. It also became comparatively easy to support multiple languages in the reactjs app.

In this post, we will try to set up multiple language support in a reactjs application using i18next and react-i18next. The first thing we need to do is to add the following dependencies using the package manager.

$ npm install react-i18next i18next --save
or 
$ yarn add react-i18next i18next --save

We need to create a file called i18n.js under /src directory. Now put the following content inside i18n.js file

i18n.js file

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

const options = {
    order: ['navigator', 'localStorage'],
    caches: ['localStorage'],
    fallbackLng: "en",
    debug: true,
    load: 'currentOnly',
    resources: {
        en: {
            translation: {
                "homepage-header": "Welcome to JavaScript"
            }
        },
        no:{
            translation: {
                "homepage-header": "Velkommen til JavaScript"
            }
        }
    },
    interpolation: {
        escapeValue: false
    }
};

i18n
    .use(initReactI18next)
    .init(options);


export default i18n;

At this point we will have to import the i18n.js file in index.js file like below:

// import i18n (needs to be bundled ;))
import './i18n';

We now are ready to apply this inside a component. Following is the App.js component to use the translation.

App.js file

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

// i18n translations might still be loaded by the http backend
// use react's Suspense
export default function App() {
    const { t, i18n } = useTranslation();


  return (
      <Suspense fallback="loading">
         <h1>{t('homepage-header')}</h1>
      </Suspense>
  );
}

Output

// Welcome to JavaScript

If we change the language to 'no' then the message changed to this: 
// Velkommen til JavaScript