Table of content
Most React applications start with English strings written directly into JSX. Adding a second language then means moving every user-facing string into message files, formatting dates and prices per locale, and handling plural rules that English does not have. react-intl is the library many teams pick for this work. This guide explains what React Intl is, how to use react-intl in a production React codebase, and how to keep its message files in a shape translators can work with.
Internationalization, abbreviated “i18n”, is the engineering work that prepares the app to support several languages without code changes. Localization, abbreviated “l10n”, is adapting it for a specific language and market, of which translation is one part. react-intl covers the i18n side and produces the files that the l10n work runs on.
The samples target react-intl 12.1.7 (React 18 or newer), @formatjs/cli 6.18.2, and eslint-plugin-formatjs 8.1.4, in a React app built with Vite and TypeScript.
What is React Intl?
React Intl is the React binding of FormatJS, a set of JavaScript libraries for formatting messages, numbers, dates, and lists. It provides React components and a hook on top of the browser’s built-in Intl APIs, and it formats translatable text with ICU MessageFormat, the message syntax defined by the Unicode project and used across Java, C++, and many JavaScript tools.
In a react-intl app:
Every translatable string is a message with an ID. A component asks for
cart.greeting, and react-intl returns the string for the active locale.Grammar is written in the message. Plurals, gender, and inline number formats are expressed in ICU syntax inside the message, which lets a translator adapt them without a code change.
The official react-intl documentation covers the full API. The sections below follow the order in which a team sets it up.
How to use react-intl: installation and IntlProvider
Install the runtime library, the CLI for message extraction, and the lint plugin:
npm install react-intl
npm install --save-dev @formatjs/cli eslint-plugin-formatjs
react-intl reads its configuration from an IntlProvider near the root of the component tree. The provider takes the active locale, the messages for that locale, and a defaultLocale that tells react-intl which language the defaultMessage strings in your code are written in.
Load only the messages for the active locale. Bundling every language into the main chunk grows the download with each language you add. Vite splits a dynamic import() with a template literal into one chunk per file:
// src/i18n.ts
export const SUPPORTED_LOCALES = ['en', 'de', 'ar'] as const;
export type Locale = (typeof SUPPORTED_LOCALES)[number];
const RTL_LANGUAGES = new Set(['ar', 'he', 'fa', 'ur']);
export function textDirection(locale: Locale): 'rtl' | 'ltr' {
return RTL_LANGUAGES.has(new Intl.Locale(locale).language) ? 'rtl' : 'ltr';
}
export async function loadMessages(locale: Locale) {
const module = await import(`../compiled-lang/${locale}.json`);
return module.default;
}
// src/App.tsx
import { useEffect, useState } from 'react';
import { IntlProvider, type MessageFormatElement } from 'react-intl';
import { loadMessages, textDirection, type Locale } from './i18n';
import { Checkout } from './Checkout';
export function App({ initialLocale }: { initialLocale: Locale }) {
const [locale, setLocale] = useState<Locale>(initialLocale);
const [messages, setMessages] = useState<Record<string, MessageFormatElement[]> | null>(null);
useEffect(() => {
loadMessages(locale).then(setMessages);
document.documentElement.lang = locale;
document.documentElement.dir = textDirection(locale);
}, [locale]);
if (!messages) return null;
return (
<IntlProvider locale={locale} defaultLocale="en" messages={messages}>
<Checkout onLocaleChange={setLocale} />
</IntlProvider>
);
}
When a message ID is missing from messages, react-intl displays the defaultMessage from the code and reports a MISSING_TRANSLATION error through the provider’s onError callback. In development that error appears in the console. In production, pass an onError handler that sends it to your logging service instead, because a missing translation then shows English text inside an otherwise German page.
Writing messages with FormattedMessage and useIntl
react-intl offers two ways to render a message. FormattedMessage is a component for text inside JSX. The useIntl hook returns an intl object for strings that have to be plain values, such as an aria-label, a placeholder, or a document title.
// src/Checkout.tsx
import { FormattedMessage, useIntl } from 'react-intl';
export function CartHeader({ firstName }: { firstName: string }) {
const intl = useIntl();
return (
<header>
<h1>
<FormattedMessage
id="cart.greeting"
defaultMessage="Welcome back, {firstName}"
description="Heading of the cart page. {firstName} is the customer's first name."
values={{ firstName }}
/>
</h1>
<input
aria-label={intl.formatMessage({
id: 'cart.coupon.label',
defaultMessage: 'Coupon code',
description: 'Accessible label of the coupon input on the cart page.',
})}
/>
</header>
);
}
Each message descriptor has three fields, and each has a job:
idis the key under which translations are stored. It is the identifier the translation workflow tracks.defaultMessageis the source text in the default locale. The CLI extracts it into the source file.descriptionis context for the translator. “Coupon code” is ambiguous on its own; a description saying it labels an input on the cart page tells the translator to use a short noun phrase.
Variables use single braces: {firstName}. For links or emphasis inside a sentence, use rich-text tags and keep the whole sentence in one message:
<FormattedMessage
id="checkout.terms"
defaultMessage="By placing the order you accept our <link>terms of sale</link>."
description="Sentence above the order button. The tagged text links to the terms page."
values={{ link: (chunks) => <a href="/terms">{chunks}</a> }}
/>
A translator can move <link> to wherever the phrase falls in their language. Splitting the sentence into three messages around the link fixes the word order to English.
Choosing message IDs
FormatJS can generate IDs from a hash of defaultMessage and description, which saves naming every string. The hash changes whenever the source text changes. A corrected typo then produces a new ID, and the existing translations for the old ID no longer match any message in the code.
Use explicit, readable IDs instead: feature.component.purpose, such as cart.coupon.label. On a codebase with several teams, prefix IDs with the feature or package name, which keeps keys unique without central coordination and makes a key’s owner obvious in the translation files.
Enforce the convention with the formatjs/enforce-id rule. The rule requires a hash pattern, and its idWhitelist option accepts IDs matching your naming scheme:
// eslint.config.js
import formatjs from 'eslint-plugin-formatjs';
export default [
formatjs.configs.recommended,
{
rules: {
'formatjs/enforce-id': ['error', {
idInterpolationPattern: '[sha512:contenthash:base64:6]',
idWhitelist: ['^[a-z][a-zA-Z0-9]*(\\.[a-zA-Z0-9]+)+$'],
}],
},
},
];
A message without an ID fails the lint run. Do not apply eslint --fix to these errors, because the rule’s autofix inserts a generated hash ID. The recommended config also enables formatjs/enforce-description, which fails any message without a translator description. Run ESLint in CI so both checks block the merge.
react-intl plural and select messages
Pluralization means changing the word form depending on a number, for example 1 item vs. 2 items. English has two forms. Arabic has six, and Polish and Russian use separate forms for numbers ending in 2 to 4. The categories each language uses come from Unicode CLDR plural rules, and react-intl applies them through ICU plural syntax:
<FormattedMessage
id="cart.itemCount"
defaultMessage="{count, plural, =0 {Your cart is empty.} one {You have # item in your cart.} other {You have # items in your cart.}}"
description="Summary line under the cart heading."
values={{ count: items.length }}
/>
# displays the number formatted for the locale. =0 matches exactly zero, and one and other are CLDR categories. A translator into Polish adds few and many branches in the translation without any code change. The ICU message syntax reference lists every argument type.
Write the complete sentence inside every branch. A message reading You have followed by a separate {count, plural, ...} message assumes English word order, and languages that place the number or the verb elsewhere cannot be translated correctly. The formatjs/prefer-full-sentence and formatjs/enforce-plural-rules rules, both in the recommended config, flag messages with leading or trailing whitespace (a sign of a sentence split across messages) and plural messages missing the one or other branch.
select chooses text by a string value, typically for grammatical gender or a role:
{role, select, admin {You can edit this project.} other {You can view this project.}}
Always include other. It is the required fallback when the value matches no branch.
Formatting dates, numbers, and currencies with react-intl
react-intl wraps the browser’s Intl.DateTimeFormat, Intl.NumberFormat, and Intl.RelativeTimeFormat and reads the locale from the provider. The same values render as 1,299.00 € in en and 1.299,00 € in de:
import { FormattedDate, FormattedNumber, FormattedRelativeTime } from 'react-intl';
<FormattedNumber value={order.total} style="currency" currency="EUR" />
<FormattedDate value={order.createdAt} dateStyle="medium" />
<FormattedRelativeTime value={-3} unit="day" numeric="auto" />
The options are the standard Intl options documented on MDN’s Intl reference. Pass the currency explicitly. The locale decides how a price is written; the currency is a property of the price itself and does not change when the user switches language.
Inside a message, use an ICU argument with a skeleton so the formatted value stays part of the translatable sentence: Your order of {total, number, ::currency/EUR} was placed on {date, date, medium}.
Component |
| Formats |
|---|---|---|
|
| ICU messages with variables, plurals, select, and rich text |
|
| Numbers, currencies, percentages, units |
|
| Dates and times |
|
| “3 days ago”, “in 2 hours” |
|
| “A, B, and C” with locale-specific conjunctions |
|
| Names of languages, regions, and currencies |
FormattedDisplayName is useful for a language switcher: formatDisplayName('de', { type: 'language' }) returns “German” in English and “Deutsch” in German.
Extracting and compiling messages
The defaultMessage strings in the code are the source of truth for the source language. The FormatJS CLI extracts them into a JSON file, which is the file translators work from, and compiles translated files into the format the app loads. The message extraction guide and the CLI reference document both steps.
FormatJS ships formatters for several translation tools, and its CLI documentation lists simple for LingoHub. The simple formatter writes each ID with its defaultMessage and drops the description, which leaves translators without the context you wrote. LingoHub’s JSON format attaches a comment to a segment through a sibling key named _<key>.comment. A custom formatter of a few lines writes descriptions in that shape:
// lingohub-formatter.mjs
export const format = (messages) => {
const output = {};
for (const [id, message] of Object.entries(messages)) {
output[id] = message.defaultMessage;
if (message.description) {
output[`_${id}.comment`] =
typeof message.description === 'string'
? message.description
: JSON.stringify(message.description);
}
}
return output;
};
Add the two steps as scripts:
{
"scripts": {
"i18n:extract": "formatjs extract \"src/**/*.{ts,tsx}\" --out-file lang/en.json --format ./lingohub-formatter.mjs",
"i18n:compile": "formatjs compile-folder --ast --format simple lang compiled-lang"
}
}
The extracted lang/en.json is flat JSON. The CLI sorts keys, which places the _-prefixed comment keys before the messages they describe:
{
"_cart.greeting.comment": "Heading of the cart page. {firstName} is the customer's first name.",
"_cart.itemCount.comment": "Summary line under the cart heading.",
"cart.greeting": "Welcome back, {firstName}",
"cart.itemCount": "{count, plural, =0 {Your cart is empty.} one {You have # item in your cart.} other {You have # items in your cart.}}"
}
Compilation uses the built-in simple formatter, because the 6.x CLI deprecates custom formatter files for the compile step. --ast precompiles each message into its parsed form, which lets the app skip parsing ICU syntax at runtime. If a file still contains _<key>.comment entries at compile time, they compile into extra entries that no component requests; remove them in a short pre-processing step if the bundle size matters to you.
Commit lang/ and generate compiled-lang/ in the build. Run i18n:extract in CI as well and fail the job when lang/en.json differs from the committed version. A pull request that adds a string without re-extracting is then caught before merge, instead of shipping a message that no translator has seen.
On a large codebase, extract per package into separate files (lang/checkout/en.json, lang/account/en.json). Each team then owns the files for its own feature, and translation progress is visible per feature.
Supporting right-to-left languages in React
react-intl formats text for Arabic or Hebrew but does not set the layout direction. The textDirection helper in the setup code sets dir="rtl" and lang on the <html> element whenever the locale changes. The browser then lays out text and inline content right to left.
Layout written with physical CSS properties does not follow the direction. Replace margin-left, padding-right, and left with the logical properties margin-inline-start, padding-inline-end, and inset-inline-start, which resolve to the correct side in both directions. Flexbox and grid rows reverse automatically under dir="rtl".
Mirror icons that express direction, such as back arrows and progress chevrons, with transform: scaleX(-1) scoped to [dir="rtl"]. Leave icons that represent real objects, such as a play button or a checkmark, unmirrored.
Test in ar as part of the regular QA pass. User-supplied content in the other direction, such as a Latin product name inside an Arabic sentence, can display in the wrong order; wrap it in a <bdi> element or pass it through as a rich-text tag so the browser isolates its direction. The W3C guidance on bidi isolation explains when isolation is needed.
Using react-intl with React Server Components
The main react-intl entry is marked as a client module, because IntlProvider and useIntl rely on React context. In a framework with Server Components, such as the Next.js App Router, import createIntl from react-intl/server in server code and format messages without a provider:
import { createIntl } from 'react-intl/server';
const intl = createIntl({ locale, messages });
const title = intl.formatMessage({ id: 'orders.title', defaultMessage: 'Your orders' });
Client components below that point still need an IntlProvider, which a small client wrapper component can supply with the same locale and messages.
Managing react-intl translations with LingoHub
The extracted source file is LingoHub’s standard JSON format, which LingoHub’s developer documentation lists as used by React Intl. Each _<key>.comment entry becomes the comment on its segment, so the description you wrote next to FormattedMessage is what the translator reads next to the text.
LingoHub’s JSON documentation uses {{ placeholder }} as the default placeholder syntax. react-intl uses ICU’s single braces, and LingoHub can recognize ICU placeholders in JSON files as well. With recognized placeholders, quality checks flag a translation in which {firstName} is missing or does not match the source string before the file returns to the repository.
An ICU plural message arrives as one segment containing the full {count, plural, ...} string. The translator edits the whole message, adds the plural categories their language needs, and keeps the argument names unchanged. That is a further reason to write complete sentences in each plural branch: the translator sees the full context of each form in one place.
The React Intl integration connects this to the rest of the workflow. LingoHub connects to the repository, pulls new and changed keys automatically after i18n:extract commits an updated lang/en.json, and opens a pull request with the translated files when they are ready. Every key in the source file is tracked across all target languages, so the exported de.json and ar.json have the same keys as the source. A glossary keeps product terminology consistent across languages, translation memory reuses earlier translations of identical strings, and AI translation with human review produces a first pass that reviewers approve.
Frequently asked questions
What is React Intl used for?
React Intl formats user-facing text, numbers, dates, and lists in React applications according to the active locale. It stores translations as ICU messages keyed by ID and provides FormattedMessage, the useIntl hook, and formatting components that wrap the browser’s Intl APIs.
react-i18next vs react-intl: which should I choose?
Both are mature React localization libraries. react-intl uses ICU MessageFormat as its native syntax and builds directly on the browser’s Intl APIs, which suits teams that want plural and select rules inside the message. react-i18next uses its own interpolation syntax with a plugin system and namespaces.
Where is the react-intl documentation?
The react-intl documentation is part of the FormatJS site at formatjs.github.io. It covers the components, the useIntl API, ICU syntax, the CLI, and the ESLint plugin. Most react-intl tutorials cover only the runtime API; the extraction and linting pages are worth reading before a project grows beyond a few hundred messages.
Does react-intl work without a build step?
Yes. IntlProvider accepts uncompiled message strings and parses ICU syntax at runtime. Precompiling with formatjs compile --ast removes that runtime parsing and lets you exclude the parser from the bundle, which matters for large message catalogs.
Conclusion
A maintainable react-intl setup combines explicit message IDs, a description on every message, complete sentences in plural and select branches, and locale-aware components for numbers and dates. Extraction in CI keeps the source file in step with the code, and logical CSS properties keep the layout correct in right-to-left languages.
LingoHub brings translation files, repository updates, quality checks, and reviews into one workflow to help you manage React localization as your app grows.
Start a free 14-day trial to try LingoHub with your own react-intl translation files. Or book a localization review to discuss your requirements with our team.
Related articles
i18n and l10n for AngularJS apps from development to deployment
Adding multiple languages to your app requires careful planning. Read our blog about i18n and l10n best practices specifically for AngularJS apps.
Gettext i18n system
What is gettext, what are its features, and what resource file types use? We highlighted all these questions in our blog. Find more inside.
i18next and react-i18next: a complete guide for React apps
Learn how to set up i18next and react-i18next in a React app: translation files, namespaces, plurals, language switching, and a production workflow.