Skip to content
Tutorials Center
My learning

Topics

Lesson 77 of 132 ยท Advanced Patterns

Internationalization

Make a React app multilingual: Intl for numbers, dates and plurals, a translation context with fallbacks, RTL layouts, react-i18next and FormatJS.

If your app has users in more than one country, the text on the screen is only the start. The same number is written 1,234.5 in the United States and 1.234,5 in Germany. March 5 is 3/5/2026 to an American and 5/3/2026 to a Briton. The word "file" has two forms in English, three in Russian and six in Arabic. Arabic and Hebrew are written from right to left, and the whole layout mirrors.

Internationalization (i18n, because there are 18 letters between the "i" and the "n") is the work of preparing software so that it can be adapted to such differences. Localization (l10n) is the adaptation itself: providing the translations and the regional settings for one locale. A locale is a language plus optional region and variants, written as a BCP 47 tag: en, en-US, pt-BR, zh-Hant-TW.

The good news is that browsers ship a powerful toolkit for the hard part: the Intl API. React adds nothing special; it is a matter of putting the right formatting calls in your components and keeping translations in a structure that React can re-render when the language changes. This lesson covers both, plus right-to-left layout, and ends with the libraries you would use in production.

Never format by hand

The most common beginner mistake is building strings with concatenation and toFixed:

JSX
<p>Total: ${price.toFixed(2)}</p>        // wrong in most countries
<p>{count} item(s) in your cart</p>      // "item(s)" is not a plural system
<p>{month}/{day}/{year}</p>              // the order is a US convention

All three are bugs outside one country. The browser knows the rules, so let it format. Intl.NumberFormat, Intl.DateTimeFormat, Intl.PluralRules, Intl.RelativeTimeFormat, Intl.ListFormat and Intl.Collator cover nearly everything. The JavaScript side of these APIs is explained in JavaScript Intl; here we focus on using them inside components.

Numbers, currencies and dates in components

A formatter takes a locale and options. The locale decides the separators and the order; the options decide what kind of value you are formatting. For currency you must say which currency: a locale is a language convention, not a money choice (a German user may shop in dollars).

Formatting with Intl in a component

Switch the select between locales. With de-DE the price reads 1.234.567,89 โ‚ฌ (dot for thousands, comma for decimals, euro sign after the number), and hi-IN groups digits the Indian way (12,34,567.89). ar-EG switches to Arabic-Indic digits (ูกูฌูขูฃูคูฌูฅูฆูงูซูจูฉ) in the Chromium-based preview, and ja-JP writes the date as 2026ๅนด3ๆœˆ5ๆ—ฅ. You wrote no locale-specific code; the data comes from the browser.

Some practical points:

  • Time zones. A Date is a moment in time; the displayed text depends on the time zone. We fixed timeZone: 'UTC' so the demo is stable. In an app you usually want the user's zone (the default) and should store timestamps in UTC.
  • Creating formatters is not free. new Intl.NumberFormat(...) parses locale data, which is measurable in a long list. Create it once per locale with useMemo, or in a module-level cache, and reuse it for every row:
JSX
const formatters = new Map();

function getMoneyFormatter(locale, currency) {
  const key = locale + '|' + currency;
  if (!formatters.has(key)) {
    formatters.set(key, new Intl.NumberFormat(locale, { style: 'currency', currency }));
  }
  return formatters.get(key);
}
  • Never parse formatted text back. Keep numbers as numbers in state; formatting is only for display. Parsing "1.234,5" is a locale problem you do not want.
  • Do not trust the default locale on the server. On a server render the "default" is the server's locale, which makes server and client HTML differ (a hydration mismatch, see Server-Side Rendering and Hydration). Pass the locale explicitly from the request.

Plurals

English has two plural categories (one and other), but this is unusual. Intl.PluralRules returns the CLDR category for a number in a given language: zero, one, two, few, many or other. Your translations then provide one string per category the language uses.

Plural categories per language

Compare the rows. English needs two forms. Russian uses 1 ั„ะฐะนะป for 1 and 21, 2 ั„ะฐะนะปะฐ for 2, and 5 ั„ะฐะนะปะพะฒ for 5, because the rule depends on the last digits (and 0 ั„ะฐะนะปะพะฒ for zero). Arabic has all six categories, even a special word for zero. A translator must be able to supply every form, so the number of forms is a property of the language, not of your code. Your job is only to ask PluralRules which category a number falls in.

There is a second set: ordinal plurals (1st, 2nd, 3rd), selected with new Intl.PluralRules(locale, { type: 'ordinal' }).

A translation dictionary with context

For the words that you write, you need a table that maps a key to the text in each language, and a way for every component to read it. That is a job for context: a provider holds the current locale and a t function, and any component reads them with a hook. When the locale changes, the provider's value changes and all consumers re-render.

Design choices that matter in practice:

  • Keys are identifiers, not the English text. cart.checkout stays valid when someone rewrites the English wording. Namespacing by feature keeps files manageable.
  • Interpolation uses placeholders, Hello, {name}, never string concatenation, because word order differs between languages.
  • Fall back to a default language when a key is missing in the current one, and in development warn loudly.
  • Whole sentences are one unit. Do not translate "You have" and "messages" separately and join them.
A translation provider with fallback

Click de: the heading, greeting and button change language together, and the third paragraph still shows English, with a console warning of the form Missing "only.english" for de, using en. That is the fallback chain at work: a missing translation should degrade to the default language, never to an empty string or a raw key in production. The plural helper is in t too: Spanish has a many category too (used for numbers like 1,000,000, where "de" is needed: "1 000 000 de artรญculos"), so the Spanish entry lists it; for 3 items the category is other.

The structure is exactly the provider pattern from Context Patterns: the memoized value changes only when the locale changes, so unrelated re-renders do not touch consumers.

Translations rarely live in the JavaScript bundle. Real projects keep one JSON file per language and load the active one on demand (dynamic import()), so a visitor downloads only the language they use. See Code Splitting with lazy and Suspense.

Relative times, lists and sorting

Three more Intl tools save you from writing language-specific code:

Relative time, lists and sorting

RelativeTimeFormat produces "yesterday" (or "ayer", "ๆ˜จๆ—ฅ") when numeric: 'auto' finds a special word, and "in 3 hours" otherwise. ListFormat inserts the right "and" and the right commas (the Oxford comma in American English, none in German). Collator sorts according to the language: German treats ร„ like A, while Swedish places it after Z. The plain .sort() compares UTF-16 code units, which puts all accented letters at the very end and is wrong for every human language. Use Intl.Collator (or localeCompare with a locale) whenever you sort text that people read.

Right-to-left layouts

Arabic, Hebrew, Persian and Urdu are written right to left (RTL). The browser handles the text itself through the Unicode bidirectional algorithm, but you must set the document direction so the layout mirrors: sidebars flip sides, list bullets move, text aligns right, and inline elements flow from right to left.

Set dir="rtl" and lang="ar" on the nearest container (ideally <html>) according to the locale. Then write your CSS with logical properties, which describe sides relative to the reading direction instead of the screen:

Physical (avoid) Logical (prefer)
margin-left margin-inline-start
padding-right padding-inline-end
text-align: left text-align: start
border-left border-inline-start
left: 0 inset-inline-start: 0
float: left float: inline-start
Direction and logical properties

Click ar: the blue bar jumps from the left edge to the right edge, the padding follows it, and the text aligns to the right. The CSS never mentions "left" or "right"; it says "start". The arrow is an example of content that is not mirrored automatically: directional icons and arrows that mean "forward" or "back" should flip, and you choose the glyph yourself. Icons that represent real objects (a phone, a clock, a play triangle for video) should not flip.

Further RTL notes:

  • Set lang as well as dir: it picks the right fonts and hyphenation and helps screen readers choose a voice.
  • Mixed text (an English product name inside Arabic text) is handled by the bidi algorithm. For user-generated content in unknown languages, use dir="auto" on the element.
  • Test RTL early. Bugs hide in absolute positioning, transforms like translateX, and animations that slide in from "the left".

Libraries for production

A hand-rolled provider is fine for learning and for small apps. A large product needs message extraction, ICU message syntax, translation management, lazy loading of catalogs and good tooling. The two most common choices are below; both are read-only here since the editor cannot install packages.

react-i18next (built on i18next) keeps translations in JSON namespaces and offers a useTranslation hook:

Terminal
npm install i18next react-i18next
JSX
import i18n from 'i18next';
import { initReactI18next, useTranslation } from 'react-i18next';

i18n.use(initReactI18next).init({
  lng: 'en',
  fallbackLng: 'en',
  resources: {
    en: { translation: { cart: { items_one: '{{count}} item', items_other: '{{count}} items' } } },
    de: { translation: { cart: { items_one: '{{count}} Artikel', items_other: '{{count}} Artikel' } } },
  },
});

function CartSummary({ count }) {
  const { t } = useTranslation();
  return <p>{t('cart.items', { count })}</p>;
}

i18next chooses the plural suffix (_one, _other, ...) with Intl.PluralRules as we did by hand.

FormatJS / react-intl uses the ICU MessageFormat standard, where plural and select rules live inside the message, which translation tools understand:

JSX
import { IntlProvider, FormattedMessage, FormattedNumber } from 'react-intl';

const messages = {
  de: {
    cart: '{count, plural, one {# Artikel} other {# Artikel}} im Warenkorb',
  },
};

function Summary({ count, total }) {
  return (
    <IntlProvider locale="de" messages={messages.de}>
      <p><FormattedMessage id="cart" values={{ count }} /></p>
      <p><FormattedNumber value={total} style="currency" currency="EUR" /></p>
    </IntlProvider>
  );
}

Frameworks add routing on top: locale prefixes in the URL (/de/cart), detection from the Accept-Language header, and hreflang links for search engines. See React Router and Framework Routers.

Locale switching in an app

A few decisions determine whether switching feels right:

  • Where does the locale come from? In order of strength: an explicit user choice (saved in a cookie or the account profile), the URL (/de/...), the Accept-Language header or navigator.languages, then a default. Our sandboxed examples cannot use storage, so they keep the locale in state.
  • Update <html lang dir> when it changes, either with an effect or by rendering the attributes on the root of the server HTML.
  • Never put translatable text in code paths that compare strings. Compare ids, not labels.
  • Allow text to grow. German and Finnish strings are often 30% longer than English; buttons and menus must wrap or grow. Pseudo-localization (replacing letters with accented, padded versions) finds layout and hardcoded-text problems before translators start.
  • Do not build sentences from fragments, and do not put markup inside strings without a rich-text mechanism (<b> tags in ICU messages, or the Trans component).
  • Dates, numbers and currencies come from Intl, with the locale and zone explicit.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should you avoid writing item(s) in a multilingual app?

    English has two categories, Russian has four, Arabic has six. Use Intl.PluralRules to find the category and keep one translated string for each.
  2. 2. What is the best way to display a price in euros to a user whose locale is de-DE?

    The locale decides separators and symbol placement, the currency option says which currency to show. Hand-built strings get the separators and the position of the symbol wrong in some locales.
  3. 3. What does a missing key in the current locale usually fall back to?

    A fallback chain lets the app degrade to the default language when a translation is missing. Log a warning in development so gaps are noticed.
  4. 4. Which CSS property keeps a left border on the start side in both English and Arabic?

    Logical properties refer to the start and end of the reading direction, so they flip automatically when dir changes to rtl. Physical properties like border-left always stay on the left side.
  5. 5. Why is names.sort() the wrong way to sort names that people read?

    Default sort order is by code unit value. Intl.Collator, or localeCompare with a locale, applies the language's real alphabetical order, which differs between German and Swedish.

Summary

  • Internationalization prepares the app for many locales; localization supplies each locale's text and formats. A locale is a BCP 47 tag such as pt-BR.
  • Use Intl.NumberFormat, Intl.DateTimeFormat, Intl.RelativeTimeFormat, Intl.ListFormat and Intl.Collator instead of manual string building; cache formatter instances and pass the locale and time zone explicitly.
  • Plurals depend on the language: ask Intl.PluralRules for the category and keep one translated string per category.
  • A translation provider in context holds the locale and a t function with interpolation, plural support and a fallback to a default language.
  • For right-to-left languages set dir and lang, write CSS with logical properties, and decide which icons should mirror.
  • Real projects use react-i18next or FormatJS, load catalogs lazily, put the locale in the URL or the profile, and test with long strings and RTL early.

Next: Client-Side Routing