Tutorial

Internationalization in React with React-Intl

Published on December 24, 2019
Default avatar

By Alex Taylor

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.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Alex Taylor

author

Still looking for an answer?

Ask a questionSearch for more help

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.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel