Member-only story

React-Intl — Message Formatting

John Au-Yeung
4 min readOct 18, 2020

--

Photo by bantersnaps on Unsplash

Many apps have to be made usable by different users from various parts of the world.

To make this easier, we can use the react-intl to do the internationalization for us.

In this article, we’ll look at how to get started with formatting messages with the react-intl library.

Message Syntax

We can format messages with placeholders and quantities.

For instance, we can write:

import React from "react";
import { IntlProvider, FormattedMessage } from "react-intl";
const messages = {
en: {
greeting: `Hello, {name}, you have {itemCount, plural,
=0 {no items}
one {# item}
other {# items}
}.`
}
};
export default function App() {
const [name] = React.useState("james");
const [itemCount] = React.useState(20);
return (
<IntlProvider locale="en" messages={messages.en}>
<p>
<FormattedMessage id="greeting" values={{ name, itemCount }} />
</p>
</IntlProvider>
);
}

to create a translation with the placeholders.

We have placeholder for name and itemCount .

The plural rules are defined by:

{itemCount, plural,
=0 {no items}
one {# item}
other {# items}
}

--

--

No responses yet