Internationalization in React with React-Intl

Alex Taylor

If you’re creating a web application that requires translation into multiple different languages, it can be difficult to implement this manually. That’s why many use internationalization (i18n) libraries, which make adding translations as simple as adding another string.

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

Installation

To start us off, we’ll create a new 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’ll open up src/App.js and add an object containing the phrases we’ll use and their translations:

src/App.js

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 and define how it will be formatted. For more information, see the documentation on message syntax.

Writing our Component

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

src/App.js

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’ve done is add an <IntlProvider>, passed-in the locale and messages to use, and used <FormattedMessage> to render our text. Unfortunately, the only thing we’re seeing is English! This is because we need some way to change the locale. This is pretty simple, just add the locale value to the component’s state and add a <select> element to pick from our four languages.

src/App.js

// -- 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;

That’s it!

Wrapping Up

That was just a simple example of how to use react-intl. It’s a very powerful library, and I definitely recommend checking out their documentation.

You can check out the complete code for this post on CodeSandbox.

  Tweet It

🕵 Search Results

🔎 Searching...

Sponsored by #native_company# — Learn More
#native_title# #native_desc#
#native_cta#