paint-brush
How to Create Multilingual React Apps with react-i18nextby@ljaviertovar
4,955 reads
4,955 reads

How to Create Multilingual React Apps with react-i18next

by L Javier TovarSeptember 15th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Internationalization (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.
featured image - How to Create Multilingual React Apps with react-i18next
L Javier Tovar HackerNoon profile picture

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:


react-i18next



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.