How To Localize React 17 App With react-intl Package

Friends, in this tutorial, we will learn how to internationalize a React app using a react-intl package.

First of all, let’s know what is internationalization.

Internationalization is the design and development of a product, application or document content that enables easy localization for target audiences that vary in culture, region, language.

Since the world has become a small place nowadays, it is easy for everyone to reach any information. So, this very concept is surely proving an asset in terms of technology and business.

In addition, just keep in mind whatever app you are working on, always remember to prioritize your target audience.

Be it a language or dialect, the application must match the requirements of a global audience. Being the product owner, we should always develop the app considering the basic needs of the local audience.

 

Throughout this guide, we will learn step by step how to build a multilingual React app using the react-intl package. Generally, React doesn’t come pre-packed with internationalization (i18n) support, but it surely is possible by using the react-intl plugin.

 

How To Localize React 17 App With react-intl Package

See below the steps for implementing the same:

Step 1- Setting Up React Project

The very first step is to create a new app by using create-react-app.

npx create-react-app react-i18n-tutorial

Next is to get into the project folder:

cd react-intl-example

Afterward, we have to start app in the browser:

npm start

 

Step 2- Starting react-intl To React 17 App

The react-intl offers i18n support and allows you to translate the content for various applications elements as number formats, dates, text paragraphs, tables, headers, buttons.

 

Then, we install react-intl plugin to localize the React application:

npm install react-intl

 

 

Following the above step will help in internationalizing the React app and it offers the below-given features:

  • Built on standards
  • Show numbers with separators
  • Shows date and time correctly
  • Show dates relative to “now”
  • Plularize labels in strings
  • Offers 150+ language support
  • Runs in the browser and Node.js

 

Step 3- Wrap React App With IntlProvider Component

In this step, we have to import the intlProvider in this step which makes internationalization quite easy. After this, we wrap React app with the <IntlProvider> component.

Further, we will open the src/Index.js file and place the below-given into it:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

import {IntlProvider} from "react-intl";

ReactDOM.render(
    <IntlProvider locale='en'>
        <App/>
    </IntlProvider>,
    document.getElementById('root')
);

serviceWorker.unregister();

 

Step 4- Wrap Text With FormattedMessage and FormattedHtmlMessage

The fourth step is to wrap the content of React app with FormattedMessage and FormattedHtmlMessage components.

Then, we open src/App.js file and import FormattedMessage and FormattedHtmlMessage components.

import React from "react";
import {FormattedMessage, FormattedHTMLMessage} from 'react-intl';

function App() {
  return (
    <div className="App">
      <p>
        <FormattedHTMLMessage
          id="app.text"
          defaultMessage="Hello, welcome {user}"
          description="Welcome message"
          values={{ user: "John Doe" }}/>
      </p>
      <a href="https://www.positronx.io" target="_blank" rel="noopener noreferrer">
        <FormattedMessage
          id="app.link"
          defaultMessage="Go to link"
          description="Check website"/>
      </a>
    </div>
  );
}

export default App;

 

We have to remember to replace the <p> HTML tag with FormattedHtmlMessage and <a> HTML tag with FormattedMessage components.Remeber that we have added the values with curly braces, this contains some text values.

We wrapped {user} value the text with FormattedMessage and FormattedHtmlMessage components to translate the text and link.

 

Step 5- Create Translations Message With Language JSON Files

Here, we will create src/translations folder in our project and create files for the locale we want to add the support in our React app.

Next, we are going to create translations files for English ad Dutch locale. Then, we will add the locale data in both locale en and locale nl files. So, we have to place the following content in our locale files:

src/translations/en/j.son:

{
    "app.text": "Hallo, welcome {user}",
    "app.link": "Go to link"
}

 

src/translations/nl/j.son:

{
    "app.text": "Hallo, welkom {user}",
    "app.link": "Ga naar link"
}

 

Now, we see that we have placed the locale files at the right place and now, IntlProvider will show the locale data as per the language shown by the browser.

Replace the final code in the src/index.js file:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

import {IntlProvider} from "react-intl";
import locale_en from "./translations/en.json";
import locale_nl from "./translations/nl.json";

const data = {
  'nl': locale_nl,
  'en': locale_en
};

const language = navigator.language.split(/[-_]/)[0];

ReactDOM.render(
  <IntlProvider locale={language} messages={data[language]}>
      <App/>
  </IntlProvider>,
  document.getElementById('root')
);

serviceWorker.unregister();

 

We need to change the browser language via settings to see how the preferred language is working in our React application.

 

Step 6- Extract Messages With babel-plugin-react-intl

We will be able to perform this task by using babel-plugin-react-intl plugins. Run the following command to install the plugins.

npm install @babel/core @babel/cli babel-plugin-react-intl --save-dev

Next is to create a .babelrc file at the root of our project folder. The babel-plugin-react-intl will keep all the extracted messages IDs in the build/message folder with associated json files.

Then, add the following code into it:

{
    "presets": ["react-app"],
    "plugins": [
        [ "react-intl", {
            "messagesDir": "./build/messages",
            "extractSourceLocation": true
        }]
    ]
}

 

Now, we go to package.json file and add either of the code inside the scripts based on our system:

"scripts": {
    "extract-messages": "set NODE_ENV=production&& babel ./src >NUL",              (Windows)
    "extract-messages": "NODE_ENV=production babel ./src  --out-file /dev/null"    (Linux/Mac)
}

 

We can use the following command to extract the messages via a babel plugin.

npm run extract-messages

 

Now, we can run our React application and try checking the different locales.

 

Summary

So, finally, we reach the conclusion of this tutorial in which we have learned the concept of internationalization (i18n). In addition, we have learnt how to translate React 17 app using the react-intl packge.

 

Leave a Reply

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