How to Create Multilingual React Apps with react-i18next

Written by ljaviertovar | Published 2023/09/15
Tech Story Tags: react | web-development | i18n | react-i18next | web-accessibility | internationalization | web-app-development | javascript

TLDRInternationalization (i18n) is crucial for making web applications accessible to users worldwide. This step-by-step guide demonstrates how to implement i18n in React applications using the react-i18next library. It covers setting up i18next, translating components, and enabling language switching to create a multilingual user experience, enhancing reach and user engagement.via the TL;DR App

As web developers, we are constantly on a quest to create applications that are both functional and accessible to users worldwide. Internationalization, or i18n, has become a crucial aspect of achieving this goal.

This technique allows us to tailor our applications to be usable in different languages and regions, significantly enhancing the user experience.

In this tutorial, we will learn what internationalization is and how to implement it with React.

What is Internationalization (i18n)?

Internationalization, often abbreviated as i18n (where ā€œiā€ stands for the first two letters of ā€œinternationalization,ā€ and ā€œ18ā€ represents the number of letters between ā€œiā€ and ā€œnā€), refers to the process of adapting an application to be both localizable and usable in different languages and regions.

It involves translating text, adapting date, time, and currency formats, and managing other cultural differences.

Why Internationalization is Important

  • Expanded Reach: By translating your application into multiple languages, you can reach a global audience, increasing its adoption and popularity.

  • Enhanced User Experience: Users feel more comfortable and engaged when interacting with an application in their native language.

  • Legal Compliance:Ā In some regions, legislation requires that applications be available in local languages.

Implementing Internationalization in React with react-i18next

React itself does not provide internationalization features, but it integrates easily withĀ i18nextĀ libraries. Two of the most popular i18next libraries for React areĀ react-i18nextĀ andreact-intl.

To illustrate how we can implement internationalization in React using theĀ react-i18nextĀ library, we’re going to build a simple application.

This application will have two buttons that will switch the application’s language between English and Spanish.

Setting Up

We will create a new React project with Vite and follow the steps indicated. This time we will useĀ pnpm, you can use the package manager of your choice.

pnpm create vite

We install the dependencies that we will need in the project:

pnpm install react-i18next i18next

  • react-i18next:Ā a library that provides integration between React and i18next.

  • i18next:Ā aĀ library for internationalization (i18n) in web applications.

    After that, we will create the following structure for the project:

...
ā”œā”€ā”€ src/
│   ā”œā”€ā”€ components/
│   │   └── Header.jsx
│   ā”œā”€ā”€ locales/
│   │   ā”œā”€ā”€ en/
│   │   │   └── global.json
│   │   └── es/
│   │       └── global.json
│   │   ...
│   ā”œā”€ā”€ App.jsx
│   ā”œā”€ā”€ main.jsx
...

Setting up i18next

We’ll start by creating the files that will contain the translated texts for our application.

src/locales/: This folder contains subfolders representing the available languages for our application. In the example, two languages are included: English (en) and Spanish (es). You can add more folders for other languages as needed.

src/locales/{idioma}/: Each language subfolder contains a JSON file that stores the specific translations for that language. File names can vary based on project needs, such as header.json or landing-page.json.

This allows for organizing translations consistently with the application’s structure.

en/globals.jsonĀ :

{
 "header": {
  "chooseLanguage": "Choose Language:"
 },
 "mainSection": {
  "title": "Creating Multilingual React Apps with react-i18next: A Step-by-Step Guide"
 }
}

es/globals.jsonĀ :

{
 "header": {
  "chooseLanguage": "Elige el idioma:"
 },
 "mainSection": {
  "title": "Creación de aplicaciones React multilingües con react-i18next: Guía paso a paso"
 }
}

Now it is time to configureĀ i18nexttogether withĀ react-i18next.

main.jsxĀ :

import ReactDOM from 'react-dom/client'

import { I18nextProvider } from 'react-i18next'
import i18next from 'i18next'

import global_en from './locales/en/global.json'
import global_es from './locales/es/global.json'

import App from './App.jsx'

import './index.css'

i18next.init({
 interpolation: { escapeValue: false },
  lng: 'auto',
  fallbackLng: 'en',
 resources: {
  en: {
   global: global_en,
  },
  es: {
   global: global_es,
  },
 },
})

ReactDOM.createRoot(document.getElementById('root')).render(
 <I18nextProvider i18n={i18next}>
  <App />
 </I18nextProvider>
)

We import the necessary dependencies and initializeĀ i18nextĀ using theĀ initĀ function.

The configuration options are as follows:

  • lng: 'auto': This configures the application’s language to be automatically detected based on the user’s browser language.

  • fallbackLng: en: If an automatic language detection fails or if a translation for the detected language is not found, the application will default to English (en).

  • resources: Translations for different languages are specified here. In this case, resources are provided for English (en) and Spanish (es) using the previously imported JSON files.

  • interpolation: { escapeValue: false }: This configuration allows disabling automatic character escaping in translations.

Finally, we wrap theĀ AppĀ component with I18nextProvider, passing theĀ i18nextĀ instance as a prop. This ensures that all components withinĀ AppĀ have access to the translations and can use internationalization in the application.

Translating Components

App.jsxĀ :

import { useTranslation } from 'react-i18next'

import Header from './components/Header'

import './App.css'

function App() {
  const { t } = useTranslation("global")

 return (
  <>
   <Header />
   <main>
        <h1>{t("mainSection.title")}</h1>
   </main>
  </>
 )
}

export default App

Importamos{ useTranslation } desde 'react-i18next'. useTranslation es hook proporcionado por 'react-i18next' que permite acceder a las funciones de traducción.

We importĀ useTranslationĀ from react-i18next.Ā The useTranslationĀ is a hook provided by react-i18next that allows access to translation functions.

Within theĀ AppĀ component, theĀ useTranslation("global")Ā hook is used. This initializes translation and provides a translation functionĀ t()that is configured to use translations from the JSON file corresponding to the translation groupĀ global.

This means that whenĀ t()Ā is called, it will look for translations in the JSON file for theĀ globalĀ group.

For example, if the translation in the JSON file forĀ mainSection.titleĀ is ā€œMain Titleā€ this header will display ā€œMain Titleā€ in the configured language.

Switching Between Languages

Header.jsxĀ :

import { useTranslation } from 'react-i18next'

export default function Header() {
  const { t, i18n } = useTranslation("global")

  return (
    <header>
      {t("header.chooseLanguage")}
      <button onClick={() => i18n.changeLanguage("en")}>EN</button>
      <button onClick={() => i18n.changeLanguage("es")}>ES</button>
    </header>
  )
}

We useĀ i18nĀ fromĀ useTranslationĀ to be able to switch between languages. We have two buttons that call theĀ changeLanguageĀ method in theirĀ onClick()Ā event, which changes the language of the application to the language passed as a parameter.

And there you have it, with this, we would have our fully multilingual application. As mentioned earlier, you can not only translate texts but also use many other functionalities for the internationalization of your application. I invite you to review the documentation.

The app looks as follows:

Demo here

Repo here

Conclusion

Internationalization is essential to reach a global audience and provide an exceptional user experience. React, along with i18n libraries like react-i18next, simplifies the implementation of internationalization in your web applications.

Make use of these tools to reach a diverse audience and enhance your users’ experience.


Read more:

Want to connect with the Author?

Love connecting with friends all around the world onĀ Twitter.

Also published here.


Written by ljaviertovar | ā˜• Full Stack developer šŸ‘Øā€šŸ’» Indie maker āœļø Tech writer
Published by HackerNoon on 2023/09/15