DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 968,547 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for React Internationalisation - Globalising your React Application
Orinameh
Orinameh

Posted on

React Internationalisation - Globalising your React Application

Websites can be accessed from any geographical location. Each location has its localised language. For applications targeting global markets, it is important to localise its language. So, a Russian, for instance, will be able to access such websites in his native Russian language. Internationalising an application is not so difficult to achieve.

In this tutorial, we will learn how to localise the language of a React application. Open your terminal/command line/command prompt and create a new react project with the [create-react-app](https://create-react-app.dev/docs/getting-started/) package.

npx create-react-app react-global
cd react-global
npm start /** or yarn start, depending on what package manager you are using**/

After starting your application, go to the browser and enter localhost:3000.

Open the project with your favourite code editor. For VS code users, ensure you are in the folder of your project and open the project with
code .

Adding Internationalisation

To add internalisation to our application, we need to add the [react-intl](https://github.com/formatjs/react-intl) package to our project. Open your terminal and type the code below

npm install react-intl --save /** yarn add react-intl**/

On successful installation, the package becomes available to us so we can start exploring its features.

The react-intl package provides react components and APIs to format dates, numbers and localise texts to different languages.

To make the internationalisation available across all our components, we need to wrap our application with the IntlProvider which is provided by the react-intl package. This is done in the entry point of our application(index.js).

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import {IntlProvider} from 'react-intl';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
    <IntlProvider locale="en">
        <App />
    </IntlProvider>, 
    document.getElementById('root')
);

The IntlProvider component takes a locale props to set the language. For now, we are using a fixed language(English en) which will later be determined dynamically from the user’s browser.

Translate Text

This is where the juicy part of the work is! React-intl provides custom components(FormattedMessage or FormattedHTMLMessage) to translate texts in a react application. To see this in action, let’s add some texts to our application in the App.js file.

import React from 'react';
import './App.css';
function App() {
  return (
    <div className="App">
      <h1>Developing a Global Application</h1>
      <p>We are using the <b>React-intl</b> language for translating texts</p>
      <p>This will help localise texts for readers in different parts of the world to        their local language</p>
    </div>
  );
}
export default App;

Let’s import FormattedMessage and FormattedHTMLMessage from react-intl and wrap around the texts we want to translate. You will see that the texts still remains in English because the default locale is still in English.

FormattedHTMLMessage is used if the text contains html elements like ,
etc while FormattedMessage should be wrapped around plain texts without html tags. Both contains an id props which helps in identifying the particular text to be translated in the .json file, defaultMessage props which contains a default text the component falls back to in case a text isn’t provided.

import React from 'react';
import {FormattedMessage, FormattedHTMLMessage } from 'react-intl'
import './App.css';
function App() {
  return (
    <div className="App">
      <h1>
        <FormattedMessage
          id="app.heading"
          defaultMessage="Developing a Global Application"
        />
      </h1>
      <p>
        <FormattedHTMLMessage
          id="app.p1"
          defaultMessage="We are using the <b>React-intl</b> language for translating           texts"
        />
      </p>
      <p>
        <FormattedMessage
          id="app.p2"
          defaultMessage="This will help localise texts for readers in different parts           of the world to their local language"
        />
      </p>
    </div>
  );
}
export default App;

We need to load the translation for each language we want to support. To do this, we need to extract each languages to a separate json file. Create a translation folder under the src folder of our project. Under, translation folder, create four json files for English, French, German and Russian translations (en.json, fr.json, ge.json and ru.json).

Then extract the text into the en.json file as shown below

en.json

{
  "app.header": "Developing a Global Application",
  "app.p1": "We are using the <b>React-intl</b> language for translating texts",
  "app.p2": "This will help localise texts for readers in different parts of the world    to their local languae" 
}

Do the same for each of the languages but with their texts translated.

You can use google translate to generate the text in the respective languages.

After generating the translation for each language, we need to import the json files into our app and pass one of the languages through the messages props in the entry of our application(index.js). The code below helps us achieve that

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import {IntlProvider} from 'react-intl';

import english from './translations/en.json';
import french from './translations/fr.json';
import german from './translations/ge.json';
import russia from './translations/ru.json';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

const message = {
    en: english,
    fr: french,
    ge: german,
    ru: russia
}
ReactDOM.render(
    <IntlProvider locale="ru" messages={message['ru']}>
        <App />
    </IntlProvider>, 
    document.getElementById('root'));

We have created a message object which is passed into the messages props in the IntlProvider. This helps us dynamically change the text of the language flag passed(e.g ru).

Visit the browser, you will see the text has translated to the Russian language we use as an example. You can go ahead to change the locale and message flag to ge or fr. To get the language of the user from the browser, create a variable language and pass the value in the locale and messages props.

/** This helps to get the language of the user from the browser **/
 const language = window.navigator.language.split(/[-_]/)[0]

Conclusion

We have successfully utilised the react-intl library for translating out text from English to other languages. To make this more interesting, you can create a select dropdown with several language options and pass it to the locale and messages props.

Top comments (0)

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.