// Tutorial //

Internationalization in React with React-Intl

Published on December 24, 2019
Default avatar
By Alex Taylor
Developer and author at DigitalOcean.
Internationalization in React with React-Intl

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

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.


Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up
About the authors
Default avatar
Developer and author at DigitalOcean.

Still looking for an answer?

Was this helpful?
1 Comments

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

You can use https://lybo.github.io/intl-translations/ to manage your translations with others.