Skip to content

Lesson 33 of 37React at scale

Internationalization in React

Ship a React app in many languages: message catalogs, ICU plurals, react-intl vs i18next vs Lingui, Intl formatting, right-to-left layouts and locale detection.

19 min read0/4 questions

The company signs its first customers in Poland and Saudi Arabia, and the product manager asks how long translation will take. You search the codebase and find 1,800 hardcoded strings, "You have " + count + " items" in the cart, dates formatted with toLocaleDateString() and no locale, and margin-left on every icon. Translation is the easy part. The hard part is that the code assumes English grammar, English number formats and left-to-right layout everywhere. Retrofitting that takes months, while building it in from the start costs a few habits. This lesson gives you those habits and the tools teams use for them.

i18n, l10n and what a locale is

Internationalization (i18n) is engineering: making the app able to work in any language and region without code changes. Localization (l10n) is content: translating and adapting it for one specific market. Your job as a React developer is mostly i18n, so that l10n becomes a matter of adding files.

A locale is identified by a BCP 47 language tag such as en-GB, pl-PL, ar-SA, pt-BR or zh-Hant-TW (language, optional script, optional region). The locale decides much more than the words:

  • Grammar: word order, plural forms, gender agreement.
  • Numbers: 1,234.5 in the US, 1.234,5 in Germany, 1 234,5 in France.
  • Dates: order, month names, first day of the week, calendar.
  • Sorting: in German Ä sorts with A, in Swedish it comes after Z.
  • Direction: Arabic, Hebrew, Persian and Urdu read right to left.

One thing the locale does not decide is currency. A user with a German browser can still be paying in US dollars. The currency comes from your data (the order, the account), and the locale only decides how it is written.

Why string concatenation breaks

"You have " + count + " items" bakes in three English assumptions: that the number goes in the middle, that "items" is the same word for every count above one, and that the sentence can be cut into pieces and glued back together. Run this to see how many plural forms different languages need:

JavaScriptplural-rules.js
const counts = [0, 1, 2, 3, 5, 11, 22, 101]; for (const locale of ["en", "pl", "ar", "ja"]) { const rules = new Intl.PluralRules(locale); console.log(`${locale}: categories ${rules.resolvedOptions().pluralCategories.join(", ")}`); console.log(" " + counts.map((n) => `${n}=${rules.select(n)}`).join(" "));}
Output
Press Run (⌘ Enter) to see what happens.

English has two forms. Polish has four: 1 produkt, 2 produkty, 5 produktów, and a fraction form. Arabic has six, including a separate dual for exactly two. Japanese has one, because nouns do not change for number. A ternary like count === 1 ? "item" : "items" is wrong for most of the world's speakers.

Predict the outputJavaScript

What does this print?

const pl = new Intl.PluralRules("pl");
console.log([1, 2, 5, 12, 22].map((n) => pl.select(n)).join(" "));
Need a nudge? Hints walk you through it.

Gluing pieces also breaks word order. "Delete " + fileName + "?" might need the name first in another language, and a translator who receives "Delete " and "?" as separate strings cannot fix that. Translate whole sentences, with placeholders.

ICU MessageFormat

The standard way to express all of this is ICU MessageFormat, which most React i18n libraries support. A message is a string with arguments in braces:

ICU messages
Hello, {name}!
 
{count, plural,
  =0 {Your cart is empty}
  one {# item in your cart}
  other {# items in your cart}
}
 
{role, select,
  admin {{name} can manage billing}
  other {{name} can view this project}
}
 
You finished {place, selectordinal, one {#st} two {#nd} few {#rd} other {#th}}
  • plural picks a branch using the locale's plural rules. =0 matches an exact number and wins over categories.
  • # is replaced by the number, formatted for the locale, so a Polish user sees 1 234 not 1234.
  • select picks a branch by a string value, used for grammatical gender, roles or any closed set. other is required as the fallback.
  • selectordinal handles "1st, 2nd, 3rd".
  • Arguments nest, so a select can contain a plural.

The English source only lists one and other. The Polish translator writes one, few, many and other, and the code does not change. That separation is the whole point: grammar lives in the message, not in your components.

Keys or source strings

There are two ways to identify a message.

Keys: t("cart.summary"), with English text in a catalog file like the other languages. Keys are stable when the English wording changes and let you group messages by feature. The downside is that code is harder to read, and people end up reusing common.open for both "Open" the verb (a button) and "Open" the adjective (a status), which many languages translate differently.

Source strings as ids: t("Your cart is empty"), with the id generated from the text. Code stays readable and extraction is automatic. The downside is that fixing a typo in English creates a new id, so every translation must be re-matched.

Either works at scale. What matters more is giving translators context: a description of where the string appears and what each placeholder holds. "Save" on a button and "Save" as in "Save 20%" are different words in most languages.

The libraries

Three libraries cover most React codebases. They all use Intl underneath and solve the same problems with different trade-offs.

react-intl (FormatJS) is built around ICU messages from the start. You write messages with an id, a defaultMessage in English and a description for translators, and a CLI extracts them into catalogs.

CartSummary.tsx (react-intl)
import { FormattedMessage, useIntl } from "react-intl";
 
export function CartSummary({ count, total }: { count: number; total: number }) {
  const intl = useIntl();
  return (
    <section aria-label={intl.formatMessage({ id: "cart.label", defaultMessage: "Shopping cart" })}>
      <FormattedMessage
        id="cart.summary"
        defaultMessage="{count, plural, =0 {Your cart is empty} one {# item} other {# items}}"
        description="Cart header. count is the number of products."
        values={{ count }}
      />
      <p>{intl.formatNumber(total, { style: "currency", currency: "EUR" })}</p>
      <FormattedMessage
        id="cart.terms"
        defaultMessage="By paying you accept the <link>terms</link>."
        values={{ link: (chunks) => <a href="/terms">{chunks}</a> }}
      />
    </section>
  );
}

Note the last message. The link is inside the sentence as a tag, so the translator can move it. Splitting it into "By paying you accept the", a link, and "." would be untranslatable.

i18next with react-i18next is the most widely used option and has a large plugin ecosystem: backends that load catalogs over HTTP, browser language detection, and many integrations. Its default format uses keys with plural suffixes chosen by Intl.PluralRules, and ICU is available through a plugin.

locales/pl/cart.json
{
  "items_one": "{{count}} produkt",
  "items_few": "{{count}} produkty",
  "items_many": "{{count}} produktów",
  "items_other": "{{count}} produktu"
}
CartSummary.tsx (react-i18next)
import { useTranslation } from "react-i18next";
 
export function CartSummary({ count }: { count: number }) {
  const { t } = useTranslation("cart");
  return <h2>{t("items", { count })}</h2>;
}

Lingui uses compile-time macros. You write the English message in JSX, and the build step turns it into an id and a catalog entry. Runtime is small because messages are compiled ahead of time.

CartSummary.tsx (Lingui)
import { Plural, Trans } from "@lingui/react/macro";
 
export function CartSummary({ count }: { count: number }) {
  return (
    <h2>
      <Plural value={count} _0="Your cart is empty" one="# item" other="# items" />
      <Trans>Free delivery on orders over 50 euros</Trans>
    </h2>
  );
}

How to choose: react-intl if you want ICU everywhere and explicit ids; i18next if you need its ecosystem or already use it on the backend; Lingui if you prefer writing English in JSX with extraction handled for you. For Next.js, the App Router has its own concerns (locale routing, Server Components), and Internationalization in Next.js covers the common choices there. Package APIs and import paths change between major versions, so follow the current docs for whichever you pick.

The translation workflow

i18n is a pipeline, not a library. A typical team runs this loop:

From a new string to a translated release
DeveloperCITranslation platformTranslatorsAppPR with new messageextract and uploadnew strings to translatetranslated catalogscompile and split per locale

The message has an English default and a description. A lint rule blocks hardcoded user-facing strings.

1/5

Two practices catch most problems before translators are even involved. Pseudo-localization replaces English with accented, longer text like [Ŷöûŕ çåŕţ îš éɱþţý ~~~~]. Any string that still shows in plain English is hardcoded, and any layout that breaks will break in German too. And a lint rule (FormatJS, i18next and Lingui all have ESLint plugins or equivalents) flags literal text in JSX.

Put it in order5 steps

Put the steps for shipping a new translatable string in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Numbers, dates and lists with Intl

Dates, times and Intl in the JavaScript & TypeScript course covered Intl.DateTimeFormat and time zones. The rest of the Intl family matters as much in a UI. These are real outputs for one amount, one date and one list:

LocaleNumberFormat EURDateTimeFormat mediumListFormat
en-US€1,234,567.89Mar 4, 2026Ana, Ben, and Chen
de-DE1.234.567,89 €04.03.2026Ana, Ben und Chen
fr-FR1 234 567,89 €4 mars 2026Ana, Ben et Chen
hi-IN€12,34,567.894 मार्च 2026Ana, Ben, और Chen

Indian grouping (12,34,567) is not a typo. That is how lakhs are written.

Match the pairs0/6 matched

Match each UI need to the Intl API that handles it.

Choose an item, then its match on the other side.

Two practical notes. Creating an Intl formatter is relatively expensive, so create it once per locale (outside the component, or with useMemo) rather than on every render of every row. And exact output can differ slightly between ICU versions in different browsers and Node releases, such as the type of space before €. Do not assert exact formatted strings in tests that run in a different environment from the one that generated them.

Right-to-left layouts

For Arabic and Hebrew the whole layout mirrors: navigation starts on the right, back arrows point right, text aligns right. If you set <html lang="ar" dir="rtl">, the browser flips text and flexbox rows for you. What it cannot flip is CSS that hardcodes a side.

Logical properties describe layout in terms of reading direction instead of left and right:

PhysicalLogicalTailwind
margin-leftmargin-inline-startms-4
padding-rightpadding-inline-endpe-4
left: 0inset-inline-start: 0start-0
text-align: lefttext-align: starttext-start
border-top-left-radiusborder-start-start-radiusrounded-ss

Switch the language below. The total row is a flex row, so it mirrors for free once dir is set. The last two lines each show a badge after the title: the first uses marginLeft, the second marginInlineStart. In Arabic, the first badge moves to the left of the title but keeps its gap on the left, so it touches the title. The logical one keeps its gap between the two.

ReactLocalizedCart.tsx
import { useState } from "react"; type Forms = Partial<Record<Intl.LDMLPluralRule, string>> & { other: string };type Locale = "en" | "pl" | "ar"; const MESSAGES: Record<Locale, { dir: "ltr" | "rtl"; title: string; items: Forms; total: string; badge: string }> = { en: { dir: "ltr", title: "Your cart", items: { one: "# item", other: "# items" }, total: "Total", badge: "new" }, pl: { dir: "ltr", title: "Twój koszyk", items: { one: "# produkt", few: "# produkty", many: "# produktów", other: "# produktu" }, total: "Razem", badge: "nowy" }, ar: { dir: "rtl", title: "سلة التسوق", items: { zero: "لا توجد منتجات", one: "منتج واحد", two: "منتجان", few: "# منتجات", many: "# منتجًا", other: "# منتج" }, total: "المجموع", badge: "جديد" },}; const BADGE = { padding: "0 6px", border: "1px solid #999" }; function plural(locale: Locale, forms: Forms, n: number) { const category = new Intl.PluralRules(locale).select(n); const template = forms[category] ?? forms.other; return template.replace("#", new Intl.NumberFormat(locale).format(n));} export default function App() { const [locale, setLocale] = useState<Locale>("en"); const [count, setCount] = useState(2); const m = MESSAGES[locale]; const total = new Intl.NumberFormat(locale, { style: "currency", currency: "EUR" }).format(count * 19.5); return ( <div> <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}> <select value={locale} onChange={(e) => setLocale(e.target.value as Locale)} aria-label="Language"> <option value="en">English</option> <option value="pl">Polski</option> <option value="ar">العربية</option> </select> <button onClick={() => setCount(Math.max(0, count - 1))}>-</button> <button onClick={() => setCount(count + 1)}>+</button> <button onClick={() => setCount(22)}>22</button> </div> <section lang={locale} dir={m.dir} style={{ marginTop: 12, padding: 12, border: "1px solid #ccc" }}> <h3 style={{ margin: 0 }}>{m.title}</h3> <p>{plural(locale, m.items, count)}</p> <p style={{ display: "flex", justifyContent: "space-between" }}> <span>{m.total}</span> <strong>{total}</strong> </p> <p> {m.title} <span style={{ ...BADGE, marginLeft: 8 }}>{m.badge}</span> </p> <p> {m.title} <span style={{ ...BADGE, marginInlineStart: 8 }}>{m.badge}</span> </p> </section> </div> );}

Try 0, 1, 2, 3, 12 and 22 in Polish and Arabic, and notice that # is formatted with the locale's NumberFormat. Plain ar uses Latin digits in most browsers, while a regional tag such as ar-EG switches to Arabic-Indic digits, which is one more reason to pass the full locale tag around. Notice too that the plural logic is one generic function: all the grammar is in the data.

Quick check
A chevron icon in a 'Next' button sits after the label with margin-left: 8px. In Arabic it touches the label on one side and has a gap on the other. What is the best fix?
Need a nudge? A hint rules out a wrong answer.

Three more layout concerns. Text expansion: German and Finnish strings are often much longer than English, so never give buttons or table columns a fixed width sized to English. User content of unknown direction, such as a name or a comment, should get dir="auto", and mixing it into a sentence is safer inside <bdi>. Fonts: check that your font stack covers Arabic, Cyrillic or CJK scripts, or the browser falls back to a system font that may not match.

Choosing and keeping the locale

Decide the locale in this order:

  1. An explicit user choice, saved to their profile or a cookie. Always offer a language picker with language names written in their own language ("Polski", not "Polish").
  2. The URL, such as /pl/pricing. It makes pages shareable and indexable per language, which matters for SEO.
  3. The browser's preference: the Accept-Language header on the server, or navigator.languages on the client, matched against the locales you support with a fallback.
  4. Your default.

Do not guess language from IP address. A traveller in Japan still reads English, and Switzerland alone has four national languages. Always set lang on <html> for the active locale; screen readers use it to choose pronunciation.

With server rendering, the server and the client must agree on the locale and the time zone, or the first client render formats dates differently from the server HTML and you get a hydration mismatch. Decide the locale on the server (from the URL or cookie), render with it, and pass it and the messages to the client so the first client render is identical. Load only the active locale's catalog, with a dynamic import() per locale.

Key terms
internationalization (i18n)
Engineering an app so it can support any language and region without code changes.
localization (l10n)
Adapting the content of an internationalized app for one market: translations, formats, imagery.
locale
A BCP 47 tag such as pl-PL or ar-SA that identifies language, optional script and region, and drives formatting rules.
ICU MessageFormat
A message syntax with placeholders, plural, select and selectordinal, used by most i18n libraries.
plural category
One of zero, one, two, few, many, other, chosen per locale by CLDR rules through Intl.PluralRules.
logical property
A CSS property such as margin-inline-start defined by reading direction, so layouts mirror automatically in right-to-left languages.
pseudo-localization
Replacing source text with accented, lengthened fake translations to find hardcoded strings and layouts that break.