React Internationalization (i18n) and Localization (l10n) : Guide

By Ronak Patel   |   29 March, 2022
React Internationalization (i18n) and Localization (l10n) : Guide

Quick Summary:

Learn how to localize React app by following proper React Internationalization processes, and following React Internationalization best practices to make your app more accessible and better suited for international markets.

App Internationalization is the process of making the contents of your app available in various languages to reach more customers and truly globalize the potential of your app. Most businesses avoid internationalization, thinking it’s too complicated and not worth the efforts behind implementing it. However, proper localization and internationalization have proven stats to highlight the impact and importance of internationalizing your app. By integrating app localization and internationalization processes, you can genuinely increase your application’s accessibility, reach, and scope.

Pro Tip: App Internationalization can also be abbreviated as – i18n, intl and App Localization is often abbreviated as – l10n.

What is internationalization in React?

React internationalization vs React Localization

React Internationalization refers to the internationalization of apps made on the React platform. React is one of the most popular app development libraries widely used by various popular brands like Facebook, Instagram, SoundCloud Pulse, Gyroscope, etc. Being a leading tech choice for building modern apps, it is important to understand how to implement internationalization in your existing or new React apps.

Top React I18N Libraries for Internationalization of React App

React has its libraries to make integrating internationalization in your React app easier. Here are some of the most popular internationalization libraries for React:

React Internationalization Libraries Description Key Features
i18next

GitHub Stats

Fork – 583

Star – 6.1k

➤ Written for JavaScript frameworks
➤ Complete localization features
➤ Comes with many plugins & integrations
➤ SaaS app for management
➤ Plugins can detect user’s language
➤ Highly scalable & sustainable
➤ Efficient API
➤ Complete ecosystem
➤ Mature Library (2011)
➤ Language Detection
➤ Complete localization
React intl (Formats)

GitHub Stats

Fork – 1.3k

Star – 13k

➤ Provides React components and API for formatting numbers, dates, strings and more.
➤ First React i18n library in the market
➤ 150+ language support
➤ Large and active community
React intl universal (Alibaba Group)

GitHub Stats

Fork – 151

Star – 1.2k

➤ Created by Alibaba Group
➤ Singleton object enables non-React components to make use of this library
➤ Can be used in various components
➤ Relatively simpler
➤ Variables in messages
➤ Supports HTML in messages
➤ Support for 150+ languages
➤ Runs in browser & Node.js

Also Read: – Best React Developer Tools

React Internationalization vs React Localization – Differences b/w I18N and L10N

React Internationalization vs React Localization.

React app internationalization is the first step, and React app localization is the second step towards making a global scale React app. First, an internationalized app is built to be tweaked and modified to support multiple languages. Then according to the client’s requirements, this internationalized app can be explicitly localized to be used in a specific language demanded by the client.

Phase #1 – React Internationalization

React Internationalization is the process of designing your React application to adapt to different languages and regions without requiring engineering changes.

Stages in React Internationalization

Product Design >Product Development >Product Testing (QA)

Stages in React Internationalization

Phase #2 – React Localization

React localization adapts internationalized React apps for a specific region/language by translating the content and adding locale-specific components.

Also Read: – Best React UI Framework You Should Know In 2022

Stages in React Localization

Product Localization>Local Testing and QA>Local Product Marketing

Stages in React Localization

Need for React App Internationalization

Internationalization is important for overcoming the language barrier for software solutions that will mostly be used by various organizations or teams spread worldwide in different regions.

react staista

As per a study conducted by Statista back in 2020, English was the most popular language used on the internet but with just 25.9% of the total market. This shows that English is not necessarily the global language for the internet. It also implies that you’re missing out on roughly 75% of internet users by not internationalizing your React app, which is a huge market opportunity to pass by.

Are you looking to hire React Native Developers?

Get dedicated React Native experts with ample experience in delivering cost-effective cross-platform mobile app solutions with Aglowid

How React Internationalization helps identify user locale

One of the most important aspects to be taken care of while internationalizing your app is to identify the user locale for getting some input as to the preferred languages of your target audience. React Internationalization has many different approaches to address this challenge.

All in all, there are three identified ways of detecting a user’s locale:

  1. Browser’s navigator. languages (on the client object)
  2. Geolocation via user’s IP address (on the server)
  3. Accept-Language HTTP header (on the server)

Ways of Detecting a User’s Locale Includes

1.Browser’s navigator.languages 

The browser’s navigator.languages is a property that returns the browser’s language version. It is a read-only property that returns a string representing the browser’s language version. Depending on the language preferences set by the user on their browser, you can set your React app’s language accordingly.

2. Geolocation via user’s IP Address 

Geolocation uses the user’s IP address to track their region and assumes the most preferred language of that location as the preferred language for the user. For instance, if the user is from Canada, through this method, the languages identified for that user are mostly going to be English and French. But what if the user coming from Canada is from a Spanish-speaking minority? This is why Geolocation is generally used as a last resort by React developers for identifying the user’s locale.

3. Accept-Language HTTP Header

By far, the Accept-Language Request Header provides a set of natural languages by the user to respond to the request. Based on this, each language is assigned a quality value representing priority or estimated numerical value of user preference for that particular language specified by that range. Overall quality value defaults to q=1.

If we take an example,

Accept-language: en-CA, ar-EG;q=0.5

This translates as “I prefer Canadian English but can accept Egyptian Arabic also”. Notice there is no 'q' value assigned to en-CA; hence the default value of q for en-CA is assumed to be '1', which is the highest preference value.

Also Read: – Top React Performance Optimization Tips in 2022

How to set up React Internationalization with i18next – A complete tutorial

Now that we understand the various concepts related to React internationalization and its importance, it is time to learn how to implement React Internationalization to make your React app genuinely global and yet localized enough for any user belonging to any language or region to understand and can use your app with ease. We will be using the i18next GitHub library as it is one of the most reliable and efficient React Internationalization libraries.

Process to setup React Internationalization with i18next

 

1. Start by creating a React App

If you already have a React app, you can skip this part. However, starting from scratch, we will first set up our React App. Here is how you Create React App (CRA):

Run this command:

npx create-react-app react-i18n-app

Next, we can start the server:

npm start

2. Install the required dependencies

The most efficient way to internationalize your React app is by using React i18next library. i18next is a widely popular React internationalization framework that is based on JavaScript. It can be used with many programming languages and frameworks, but it is most compatible with React. To fully utilize the potential of React i18next library, we will have to install some supporting libraries:

Start by installing i18next:

npm install react-i18next --save

Next, we need a backend library to help us fetch translations from a source directory and a language detector that helps identify the users’ language. Run this command:

npm i i18next-HTTP-backend i18next-browser-language detector

Now, we need to install React Bootstrap for styling requirements:

npm install react-bootstrap@next bootstrap@5.1.0

3. Build the Main Page

Next, we will create our React app’s main page before starting internationalization. Here we will build all the necessary components needed for our React app.

Navigation Bar

Any web app needs the navigation component. To create src/components/Navigation.js, write the following code:

import { Container, Nav, Navbar, NavDropdown } from "react-bootstrap";

function Navigation () {
    
  return (
    <Navbar bg="light" expand="lg">
      <Container>
        <Navbar.Brand href="#">React i18n</Navbar.Brand>
        <Navbar.Toggle aria-controls="basic-navbar-nav" />
        <Navbar.Collapse id="basic-navbar-nav">
          <Nav className="me-auto">
            <NavDropdown title="Language" id="basic-nav-dropdown">
              <NavDropdown.Item href="#">English</NavDropdown.Item>
              <NavDropdown.Item href="#">French</NavDropdown.Item>
            </NavDropdown>
          </Nav>l
        </Navbar.Collapse>
      </Container>
    </Navbar>
  );
}

export default Navigation;

Heading

Next, let’s create the src/components/Greeting.js with this code:

function Greeting () {

  return (
    <h1>Hey </h1>
  );
}

export default Greeting;

Text

Create the text component – src/component/Text.js:

function Text () {

  return (
    <p> Thank you for visiting our app.</p>
  )
}

export default Text;

Now, to show these components on the web app you need to change the content of src/App.js:

import React from 'react';
import { Container } from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import Greeting from './components/Greeting';
import Loading from './components/Loading';
import Navigation from './components/Navigation';
import Text from './components/Text';

function App() {

  return (
    <>
      <Navigation />
      <Container>
      	<Greeting />
      	<Text />
      </Container>
    </>
  );
}

export default App;

Connect to the server and run this code; it will display a simple web app with a navigation bar and the text that we added as components.

Also Read: – Top React Chart Libraries to Visualize your Data in 2022

4. Set up i18next for React Internationalization

Now that you are ready with a properly functioning React web app, we will set up i18next for configuring and initializing it.

Start by creating the path src/i18n.js by running the following code:


import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import I18nextBrowserLanguageDetector from "i18next-browser-languagedetector";
import Backend from 'i18next-http-backend';

i18n
  .use(I18nextBrowserLanguageDetector)
  .use(Backend)
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    fallbackLng: 'en',
    debug: true,

    interpolation: {
      escapeValue: false // react already safes from xss
    }
  });

  export default i18n;

Here we imported i18n from i18next. Then we also added the language detector and backend plugin to the i18n. Moreover, we installed the initReactI18next plugin for connecting i18n with our React app.

Now we initialize i18n by passing it an object of options. You can pass a list of options to the initializer. For this project, we will pass three options:

fall backing – if no language is detected in i18n, this function acts as the default language. When interacting with the web app, this language is detected from the user’s preferred language or based on their previously chosen language.

debug – By default, this function enables debug messages in the console. React developers need not use this during the production stages.

The escapeValue in interpolation should be set to false since React is safe from cross-site-scripting (XSS).

LookinG for React developers to hire?

Get in touch to develop highly scalable web app project

5. Add Translation Files

The i18next-HTTP-backend plugin will search for translation files in the directory – public/locales/{language}/translation.json. Here the {language} portion would contain the code abbreviation for the chosen language. For instance, “en" if it’s English and "ca" if it’s Canadian English and so on.

We will add two languages for our sample React project – English (en) and Danish(da). Hence, we need to create a locales directory, and under it, we create two directories, en and da.

Now, you should create a file named translation.json inside each language variant. First, we start with adding translation.json in the en file:


{
  "greeting": "Hey",
  "text": "Thank you for visiting our app.",
  "language": "Language"
}

By doing so, you create three translation keys. When you utilize these keys, the associated string value of the key will be outputted on the chosen language. Hence, we need to provide the duplicate keys in all language files, but the values should be translated to match that language.

Keeping this in mind, we create the translation.json inside da file:


{
 "greeting": “hej”,
 "text": " Tak" fordi du besøgte vores app.”,
 "language": "sprog"
}

6. The i18n instance is ready to be used

Now that we have the i18n file created in App.js, we need to import it into our React project:

import i18n from './i18n';

After importing the i18n instance and the translation files, we need to ensure the components get rendered. For this we make use of React’s Suspense for Data Fetching:


<Suspense fallback= {<Loading />}>
	<Navigation />
	<Container>
		<Greeting />
        <Text />
    </Container>
</Suspense>

Here we pass the Loading component as a fallback attribute when i18next loads alongside the translation files. Since we are adding a new component via loading, we need to create a new directory – src/components/Loading.js with the following code:


import { Spinner } from "react-bootstrap";

function Loading () {
  return (
    <Spinner animation="border" role="status">
      <span className="visually-hidden">Loading...</span>
    </Spinner>
  )
}

export default Loading;

We can translate the strings from the App components and sub-components with this.

7. Translate Strings by using the useTranslation function

Translation strings can be used in various ways in i18next. One of the most preferred methods by React developers is to use the useTranslation hook. With this method, you can translate strings easily.

Let’s start by translating the Greeting component:


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

After adding this code in the beginning of the ‘Greeting’ component, we replace the inside content of the returned JSX from “Hey” to the translation function we just introduced t from userTranslation:


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

Next, we repeat the same process for other components such as Text:


import { useTranslation } from "react-i18next";
function Text () {
  const { t } = useTranslation();

  return (
    <p>{t('text')}</p>
  )
}

export default Text;

Now the navigation component also has text element as “Language”. We will translate the text of the ‘Language’ portion as well:

<NavDropdown title={t('language')} id="basic-nav-dropdown">

Now, if we check the web app’s frontend, we’d notice nothing changed, and the content is still in English. However, since we used the translation function passing, it’s critical instead of the actual strings. We can see that it is outputting the right strings; it shows that the i18next is correctly loading translations, showing the correct language on the front end.

Note – nothing will change if you try to change the website’s language by utilizing the dropdown menu we had set earlier during the initial phase. Though we have added different language files to our backend, we haven’t connected that functionality to change the language based on the language clicked by the user yet.

Also Read: – React SEO Guide

8. Enable changing the website language

Your user should have access to change the language of the React website. For this, we need to set up a context that all parts of our React web app can access. Creating a ‘context’ eliminates the need to pass any state through various components/levels.

Start by creating the file – src/LocaleContext.js by adding the following code:


import React from "react";

const defaultValue = {
  locale: 'en',
  setLocale: () => {} 
}

export default React.createContext(defaultValue);

Now create the state locale inside the src/App.js directory:

function App() {
  const [locale, setLocale] = useState(i18n.language);

Here we are passing i18n.language as an initial value. The language property is a representation of the current language chosen. The overall time for the i18n to load with all translations will be longer; hence the initial value will remain undefined. Hence, we need to utilize the languageChanged event triggered by i18n when the language is initially loaded and when it changes.

i18n.on('languageChanged', (lng) => setLocale(i18n.language));

Now, we should surround the returned JSX with context provider:

<LocaleContext.Provider value={{locale, setLocale}}>
      <Suspense fallback={<Loading />}>
        <Navigation />
          <Container>
            <Greeting />
            <Text />
          </Container>
	</Suspense>
</LocaleContext.Provider>

You will now be accessing the locale and setters via any subcomponents. Now for changing the language, you still need a listener function that triggers language change from click events on the dropdown links from the navigation bar. For this, we will fetch the locale state from the context at the start of the function:

const { locale } = useContext(LocaleContext);

Doing so adds a listener component that will change the language in i18n:

function changeLocale (l) {

if (locale !== l) {

i18n.changeLanguage(l);

}

}

Now we bind the listener to the click event for both dropdown items (English and Danish):

<NavDropdown.Item href="#" onClick={() => changeLocale('en')}>English</NavDropdown.Item>
              <NavDropdown.Item href="#" onClick={() => changeLocale('da')}>Danish</NavDropdown.Item>

Now when you will go on the web app and change language, you will see the translated page based on the language you choose. Even when you refresh the page after setting your preferred language, the page will stay in the same language unless you change it intentionally using the other dropdown item manually.

9. Shift the location of Translation Files

Your translation files are by default located in the public/locales/{language}/translation.json directory. However, you can change this if you want.

To change the location of your translation files, change .use(Backend) in src/i18n.js directory to the following:

.use(new Backend(null, {

loadPath: '/translations/{{lng}}/{{ns}}.json'

}))

Here the loadPath is relative to the public. Using the path mentioned above, you can shift the translation files to a directory labeled translations. You can also change the value of a loadPath to prioritize language as the first parameter and namespace as second.

have a unique app Idea?

Hire Certified Developers To Build Robust Feature, Rich App And Websites.

Wrapping up!

You finally have an internationalized React app that can be easily localized as per different languages and regions, making your app much more accessible to people around the globe, expanding your target audience, generating better revenue streams and making your business truly global.

Get in Touch!

Ronak Patel

Ronak Patel is a CEO and Founder of Aglowid IT Solutions, an ever-emerging Top Web and Mobile Development company with a motto of turning clients into successful businesses. He believes that Client's success is company's success and so that he always makes sure that Aglowid helps their client's business to reach to its true potential with the help of his best team with the standard development process he set up for the company.

Related Posts