React JS: Handle Internationalization and Localization with Example Tutorial

Internationalization (i18n) and localization (l10n) are important aspects of creating applications that can be used by people from all over the world. In this tutorial, we will learn how to implement internationalization and localization in a ReactJS application using the react-i18next library. We will walk through the process of setting up the library, loading translations and using the useTranslation hook and Trans the component in our components and templates.

Suppose we have a ReactJS application that is being used by people from different countries. We want to make sure that our application can be easily translated into different languages to cater to our global audience. We need a way to handle internationalization and localization in our ReactJS application.

 

How to Translation Feature in React App using the react-i18next library?

Follow these quick steps to implement internationalization and localization in react app easily:
Step 1 – Install the react-i18next library
Step 2 – Create a translation file
Step 3 – Set up i18n
Step 4 – Use translations in components
Step 5 – Use translations in templates
Step 6 – Switch languages

 

Step 1 – Install the react-i18next library

To get started with internationalization and localization in ReactJS, we need to install the react-i18next library. You can install it using npm:

npm install react-i18next i18next

 

Step 2 – Create a translation file

Create a JSON file to store translations. Here’s an example of a translation file for English:

{
  "welcome": "Welcome to my app!",
  "buttonLabel": "Click me"
}

 

Step 3 – Set up i18n

Create an instance of the i18n object and configure it with the translations. Here’s an example:

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

import translationEN from './translations/en.json';

i18n
  .use(initReactI18next) // bind react-i18next to the instance
  .init({
    resources: {
      en: {
        translation: translationEN,
      },
    },
    lng: 'en',
    fallbackLng: 'en',

    interpolation: {
      escapeValue: false,
    },
  });

export default i18n;

In this example, we’ve imported the initReactI18next function from the react-i18next library and passed it to the use() method of the i18n object. We’ve also configured the resources property with the translations, set the default language to English, and set the fallbackLng property to English as well.

 

Step 4 – Use translations in components

To use translations in our components, we can use the useTranslation hook. Here’s an example:

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

function App() {
  const { t } = useTranslation();

  return (
    <div>
      <h1>{t('welcome')}</h1>
      <button>{t('buttonLabel')}</button>
    </div>
  );
}

export default App;

In this example, we’ve imported the useTranslation hook from the react-i18next library and used it to get the t function. We’ve then used the t function to translate the text inside the h1 and button tags.

 

Step 5 – Use translations in templates

To use translations in our templates, we can use the Trans component. Here’s an example:

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

function App() {
  return (
    <div>
      <Trans i18nKey="welcome">
        Welcome to my <strong>app</strong>!
      </Trans>
      <button>
        <Trans i18nKey="buttonLabel">Click me</Trans>
      </button>
    </div>
  );
}

export default App;

In this example, we’ve imported the Trans component from the react-i18next library and used it to translate the text inside the component. We’ve also used the i18nKey prop to specify the translation key and the strong tag to mark up the text.

 

Step 6 – Switch languages

To switch languages, we can use the i18n object. Here’s an example:

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

function App() {
  const { t } = useTranslation();

  const handleLanguageChange = (lng) => {
    i18n.changeLanguage(lng);
  };

  return (
    <div>
      <h1>{t('welcome')}</h1>
      <button onClick={() => handleLanguageChange('en')}>
        English
      </button>
      <button onClick={() => handleLanguageChange('fr')}>
        French
      </button>
    </div>
  );
}

export default App;

In this example, we’ve imported the i18n object and used it to switch languages in the handleLanguageChange function. We’ve also used the onClick prop to bind the function to the buttons.

 

Some Common Issue with Solutions:

Developers may face various questions, issues, and features while using react-i18next. Here are some common ones and their solutions with example code snippets.

1 – How to set the default language?

To set the default language, we can use the i18n object. Here’s an example:

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import translationEN from './locales/en/translation.json';
import translationFR from './locales/fr/translation.json';

const resources = {
  en: {
    translation: translationEN,
  },
  fr: {
    translation: translationFR,
  },
};

i18n.use(initReactI18next).init({
  resources,
  lng: 'en',
  interpolation: {
    escapeValue: false,
  },
});

export default i18n;

In this example, we’ve imported the i18n object and used it to set the default language to en. We’ve also loaded the translations from JSON files and used the initReactI18next function to initialize the react-i18next library.

 

2 – How to load translations asynchronously?

To load translations asynchronously, we can use the useTranslation hook with the initReactI18next function. Here’s an example:

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

function App() {
  const { t, i18n } = useTranslation();

  if (i18n.language === 'en') {
    import('./locales/en/translation.json').then((res) => {
      i18n.addResourceBundle('en', 'translation', res.default, true, true);
    });
  } else if (i18n.language === 'fr') {
    import('./locales/fr/translation.json').then((res) => {
      i18n.addResourceBundle('fr', 'translation', res.default, true, true);
    });
  }

  return <h1>{t('welcome')}</h1>;
}

export default App;

In this example, we’ve used the import function to load the translations asynchronously based on the current language. We’ve also used the addResourceBundle function to add the translations to the i18n object.

 

3 – How to use placeholders?

To use placeholders, we can use the t function with the interpolation option. Here’s an example:

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

function App() {
  const { t } = useTranslation();

  return (
    <div>
      <h1>{t('welcome')}</h1>
      <p>{t('greeting', { name: 'John' })}</p>
    </div>
  );
}

export default App;

In this example, we’ve used the t function to translate the text and pass a variable named name to the translation using the interpolation option.

 

4 – How to use plurals?

To use plurals, we can use the t function with the count option. Here’s an example:

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

function App() {
  const { t } = useTranslation();

  return (
    <div>
      <p>{t("book", { count: 0 })}</p>
      <p>{t("book", { count: 1 })}</p>
      <p>{t("book", { count: 2 })}</p>
    </div>
  );
}

export default App;

In this example, we‘ve used the `t` function to translate the text and passed a variable named `count` to the translation using the `count` option. The translation file should contain translations for each number of items.

 

5 – How to change the language dynamically?

To change the language dynamically, we can use the `i18n` object to change the language. Here‘s an example:

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

function App() {
  const { t } = useTranslation();

  const changeLanguage = (lng) => {
    i18n.changeLanguage(lng);
  };

  return (
    <div>
      <h1>{t('welcome')}</h1>
      <button onClick={() => changeLanguage('en')}>English</button>
      <button onClick={() => changeLanguage('fr')}>French</button>
    </div>
  );
}

export default App;

In this example, we’ve used the changeLanguage function of the i18n object to change the language when a button is clicked.

 

6 – How to use namespaces

To use namespaces, we can use the useTranslation hook with the ns option. Here’s an example:

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

function App() {
  const { t } = useTranslation(['common', 'dashboard']);

  return (
    <div>
      <h1>{t('common:welcome')}</h1>
      <p>{t('dashboard:title')}</p>
    </div>
  );
}

export default App;

We’ve used the useTranslation hook with the common and dashboard namespaces. We’ve also used the namespace name as a prefix in the translation key to specify which namespace to use.

 

 

Conclusion

In this tutorial, we’ve learned how to handle internationalization and localization in a ReactJS application using the react-i18next library. We’ve walked through the process of setting up the library, loading translations, and using the useTranslation hook and Trans component in our components and templates. We’ve also learned how to switch languages using the i18n object. By following these steps, you can easily create a multilingual ReactJS application that can cater to a global audience.

Leave a Comment

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