/  Technology   /  Internationalization in React with React-Intl
Internationalization in React with React-Intl

Internationalization in React with React-Intl

 

If you are creating a web applications that requires translation into multiple different languages, and  it can be difficult to implement this manually. That is why more use internationalization (i18n) packages, and which make adding translations as simple as adding another string.

React-Intl, part of the FormatJS set of libraries(packages), is a nice library for doing just that. Written by the folks over at Yahoo, and it provides several React components that allow for translating strings, formatting dates, numbers, and more.

Installation

To start us off, we will create a new react project using Create React App and add the react-intl package.

$ yarn create react-app i18n
$ cd i18n
$ yarn add react-intl

Adding Translations

First, we will open up src/App.js and add an object containing the phrases we will use and their translations:

import React from "react";
const messages = {
  en: {
    greeting: "Hello {name}! How are you?",
    time: "The time is {t, time, short}.",
    date: "The date is {d, date}."
  },
  es: {
    greeting: "¡Hola {name}! ¿Cómo estás?",
    time: "La hora es {t, time, short}.",
    date: "La fecha es {d, date}."
  },
  fr: {
    greeting: "Bonjour {name}! Comment ça va?",
    time: "Il est {t, time, short}.",
    date: "La date est {d, date}."
  },
  de: {
    greeting: "Hallo {name}! Wie geht's?",
    time: "Es ist {t, time, short} Uhr.",
    date: "Das Datum ist {d, date}."
  }
};

The arguments enclosed in curly braces ({ and }) allow you to input data field, and define how it will be formatted.

Writing our Component

Now that we have our translations written, and we have to use them in our react App component.

import React, { useState } from "react";
import { IntlProvider, FormattedMessage } from "react-intl";
const messages = {
  // -- snip --
};
function App() {
  const [name, setName] = useState("");
  const handleChange = e => {
    setName(e.target.value);
  };
  const locale = "en";
  return (
    <>
      <input placeholder="Enter name" onChange={handleChange} />
      <IntlProvider locale={locale} messages={messages[locale]}>
        <p>
          <FormattedMessage id="greeting" values={{ name }} />
          <br />
          <FormattedMessage id="time" values={{ t: Date.now() }} />
          <br />
          <FormattedMessage id="date" values={{ d: Date.now() }} />
        </p>
      </IntlProvider>
    </>
  );
}
export default App;

Great! What we have done is add an <IntlProvider>, and passed-in the locale and messages to use, and used <FormattedMessage> to render our text. Unfortunately, the only thing we are seeing is English! This is because we want some way to change the locale. This is pretty simple, just add the locale value to the react component’s state and add a <select> element to pick from our four languages.

// -- snip --
function App() {
  const [name, setName] = useState("");
  const handleChange = e => {
    setName(e.target.value);
  };
  const [locale, setLocale] = useState("en");
  const handleSelect = e => {
    setLocale(e.target.value);
  };
  return (
    <>
      <input placeholder="Enter name" onChange={handleChange} />
      <select onChange={handleSelect} defaultValue={locale}>
        {["en", "es", "fr", "de"].map(l => (
          <option key={l}>{l}</option>
        ))}
      </select>
      <IntlProvider locale={locale} messages={messages[locale]}>
        <p>
          <FormattedMessage id="greeting" values={{ name }} />
          <br />
          <FormattedMessage id="time" values={{ t: Date.now() }} />
          <br />
          <FormattedMessage id="date" values={{ d: Date.now() }} />
        </p>
      </IntlProvider>
    </>
  );
}
export default App;

 

Leave a comment