Internationalisation (i18n) in React

Internationalization, often abbreviated as i18n (with 18 representing the number of letters between the first and last letter of the word), refers to the process of designing your application so that it can easily adapt to different languages and regions without requiring major changes to the underlying code. In the context of React.js, i18n involves making your React components capable of displaying text, dates, currencies, and other locale-specific content in the correct format based on the user's language preferences.

Understanding Internationalization (i18n)

What is Internationalization?

Internationalization (i18n) is the process of preparing an application for localization, meaning adapting it for different languages, cultures, and regions. It’s the backbone that allows your React application to present text, dates, currencies, and other elements correctly for users in different locales.

  • Localization (l10n): The process of actually translating and formatting content for a specific locale. For example, translating English text into French and adjusting date formats from “MM/DD/YYYY” to “DD/MM/YYYY.”

  • Locale: A locale is a combination of language and region (e.g., “en-US” for English in the United States or “fr-FR” for French in France).

Why is i18n Important?

As the internet becomes increasingly global, building applications that support multiple languages and regions is essential for a global audience. Internationalization allows your app to be flexible and inclusive, improving accessibility and user satisfaction.

Setting Up Internationalization in React

There are several libraries available for implementing i18n in React, but one of the most popular and comprehensive is react-i18next. This library is built on top of the i18next framework and provides seamless integration for React apps.

Installing the Required Packages

To get started with react-i18next, install the following packages.

				
					npm install i18next react-i18next i18next-browser-languagedetector

				
			
  • i18next: A popular framework for internationalization in JavaScript.
  • react-i18next: Provides integration between React and i18next.
  • i18next-browser-languagedetector: Detects the user’s language automatically (e.g., based on their browser settings).

Initializing i18next in a React App

To initialize i18next in your React app, you need to configure it with the languages you want to support and how to load translations.

Example: Initializing i18next

				
					// src/i18n.js
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';

// Translation files
const resources = {
  en: {
    translation: {
      welcome: "Welcome to my app",
      description: "This is an example of i18n in React.",
    },
  },
  fr: {
    translation: {
      welcome: "Bienvenue sur mon application",
      description: "Ceci est un exemple d'i18n dans React.",
    },
  },
};

i18n
  .use(LanguageDetector) // Automatically detect the user's language
  .use(initReactI18next) // Passes i18n down to react-i18next
  .init({
    resources,
    fallbackLng: 'en', // Default language if none is detected
    interpolation: {
      escapeValue: false, // React already escapes by default
    },
  });

export default i18n;

				
			

Explanation:

  • We define our translations in the resources object, where en is for English and fr is for French.
  • LanguageDetector automatically detects the user’s language, and fallbackLng specifies the fallback language (English in this case) if no language is detected.
  • The i18n object is initialized with the translations and passed to react-i18next.

Using Translations in React Components

Once i18n is initialized, you can start using translations in your React components. The useTranslation hook from react-i18next is a simple way to get access to translation functions within your components.

Displaying Translations

The t function provided by useTranslation is used to fetch the translation for a given key.

Example: Using Translations in a Component

				
					// src/components/Welcome.js
import React from 'react';
import { useTranslation } from 'react-i18next';

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

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

export default Welcome;

				
			

Explanation:

  • We use the useTranslation hook to get the t function, which allows us to access the translation keys defined in our i18n.js.
  • The t('welcome') and t('description') will automatically fetch the corresponding text in the current language.

Output:

  • If the language is set to English (en):

				
					Welcome to my app
This is an example of i18n in React.
				
			

If the language is set to French (fr):

				
					Bienvenue sur mon application
Ceci est un exemple d'i18n dans React.
				
			

Switching Languages

To provide users with the ability to switch between languages, you can use the i18n.changeLanguage() method.

Creating a Language Switcher

You can create a simple dropdown to switch between languages.

Example: Language Switcher Component

				
					// src/components/LanguageSwitcher.js
import React from 'react';
import { useTranslation } from 'react-i18next';

function LanguageSwitcher() {
  const { i18n } = useTranslation();

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

  return (
    <div>
      <button onClick={() => changeLanguage('en')}>English</button>
      <button onClick={() => changeLanguage('fr')}>Français</button>
    </div>
  );
}

export default LanguageSwitcher;

				
			

Explanation:

  • The changeLanguage function from the i18n object changes the language to the one specified (en for English, fr for French).
  • When a user clicks on the button, the app switches to the selected language.

Output:

When a user clicks the “Français” button, the app will display all text in French, and clicking “English” will switch it back to English.

Handling Pluralization and Dynamic Content

Pluralization in Translations

Many languages require different word forms depending on the number of items. react-i18next supports pluralization using keys like key_plural for plural forms.

Example: Handling Pluralization

				
					// src/i18n.js
const resources = {
  en: {
    translation: {
      items: "You have {{count}} item",
      items_plural: "You have {{count}} items",
    },
  },
  fr: {
    translation: {
      items: "Vous avez {{count}} article",
      items_plural: "Vous avez {{count}} articles",
    },
  },
};

				
			
				
					// src/components/ItemCount.js
import React from 'react';
import { useTranslation } from 'react-i18next';

function ItemCount({ count }) {
  const { t } = useTranslation();

  return <p>{t('items', { count })}</p>;
}

export default ItemCount;

				
			

Explanation:

  • We define items for singular and items_plural for plural cases.
  • In the ItemCount component, t('items', { count }) automatically chooses the correct translation based on the count.

Output:

  • If count is 1: “You have 1 item.”
  • If count is 5: “You have 5 items.”

Interpolation of Dynamic Content

We can also interpolate dynamic values directly into our translations using {{variable}}.

Example: Interpolating Dynamic Content

				
					const resources = {
  en: {
    translation: {
      greeting: "Hello, {{name}}!",
    },
  },
};

				
			
				
					function Greeting({ name }) {
  const { t } = useTranslation();

  return <h1>{t('greeting', { name })}</h1>;
}

				
			

Explanation:

  • In this example, t('greeting', { name }) interpolates the name variable into the translation string.

Output:

If name is “John”, the output will be:

				
					Hello, John!

				
			

Advanced i18n Concepts

Lazy Loading Translations

For performance reasons, you may not want to load all translation files upfront. Instead, you can lazy-load them based on the user’s selected language.

				
					i18n
  .use(initReactI18next)
  .init({
    lng: 'en',
    fallbackLng: 'en',
    load: 'languageOnly',
    backend: {
      loadPath: '/locales/{{lng}}.json',
    },
  });

				
			

Explanation:

  • The loadPath option tells i18next to load translation files dynamically from the specified path.

Internationalization (i18n) is a vital aspect of modern web development, especially for applications targeting a global audience. In this chapter, we covered the basics of internationalization in React, including setting up react-i18next, managing translations, handling pluralization, dynamic content, and language switching. By implementing these techniques, you can ensure that your React app is prepared to serve users from various locales, improving accessibility and user experience. Happy Coding!❤️

Table of Contents