React

React Localization

Localize a React application with React Intl: mark the strings, extract them into a resource file, translate it in Soluling, and import the localized files into your application.

React has no built-in localization, so you use a library. This guide uses React Intl, part of FormatJS. Soluling reads the file that the extract tool writes, shows plurals and selects in a pattern editor, checks the placeholders, and writes the runtime files. Translate in Soluling Desktop or in a browser with Soluling Cloud. The guide follows the Driving sample, a small driving time calculator.

Try Soluling

Resources JSON en.json Soluling Original (English) Translation (Finnish) Driving Time Driving distance Driving speed Calculate Driving time is # # =0 one # hour other # hours one # minute other # minutes Ajoaika Ajomatka Nopeus Laske Ajoaika on # # =0 one # tunti other # tuntia one # minuutti other # minuuttia The strings in en.json have been translated Localized resources JSON en.json fi fi.json de de.json ja ja.json A localized JSON file for each language, imported by the application Resources JSON en.json Soluling Original (English) Translation (Finnish) Driving Time Driving distance Driving speed Calculate Driving time is # # =0 one # hour other # hours one # minute other # minutes Ajoaika Ajomatka Nopeus Laske Ajoaika on # # =0 one # tunti other # tuntia one # minuutti other # minuuttia The strings in en.json have been translated Localized resources JSON en.json fi fi.json de de.json ja ja.json A localized JSON file for each language, imported by the application
Unlike Angular's standard build, one React build holds every language you import, and the application chooses at runtime.
Input
The resource file of formatjs extract (en.json)
Output
Localized runtime files (fi.json, de.json, ja.json) that the application imports
Runtime
IntlProvider gets the messages of the browser's language
Cloud
Upload en.json to Soluling Cloud directly; no desktop step needed

On this page

Tutorial

Localize a React application, step by step

Six steps take the Driving sample from an English-only application to a multilingual one.

01

Prepare: mark the strings with React Intl

Install the library with npm install react-intl, and wrap the application in IntlProvider. Then mark every text the user sees:

  1. JSX text: FormattedMessage. Change <h1>Driving Time</h1> to <h1><FormattedMessage id="drivingTime" defaultMessage="Driving Time" /></h1>. The Driving sample gives each text a short id, so a translation stays with its text when you change the wording.
  2. Attributes and code: formatMessage. FormattedMessage renders an element, so it can't be used in an attribute. Get intl with the useIntl hook and write title={intl.formatMessage({ id: 'distanceHint', defaultMessage: 'Distance in kilometers' })}. Use the same for strings in code, such as the page title. A class component gets intl with injectIntl.
  3. Patterns: values. A text with placeholders also needs the values.
  4. Comments: description. Describe every placeholder for the translator, for example, description="hours, minutes: The driving time".
  5. Plurals and selects. Use ICU expressions, such as {hours, plural, one {# hour} other {# hours}}, instead of building sentences from pieces. See patterns.
Marking the texts with React Intl Before, the heading, tooltip, and result are hard-coded English. After, the heading uses FormattedMessage, the tooltip uses formatMessage, and the result is a plural pattern. The extracted file has the texts, with Finnish translations. Before: original\src\App.jsx <h1>Driving Time</h1> <input title="Distance in kilometers" /> <p>Driving time is {result.hours} hour(s) {result.minutes} minute(s)</p> ✕ Stays English, no plural forms Internationalize After: react-intl\src\App.jsx <h1><FormattedMessage id="drivingTime" defaultMessage="Driving Time" /></h1> <input title={intl.formatMessage({ id: 'distanceHint', defaultMessage: 'Distance in kilometers' })} /> <FormattedMessage id="result" defaultMessage="Driving time is {hours, plural, ...}" values={result} /> en.json and fi.json in Soluling drivingTime Finnish Ajoaika result English Driving time is {hours, plural, =0 {} one {# hour} other {# hours}} {minutes, plural, ...} Finnish Ajoaika on {hours, plural, =0 {} one {# tunti} other {# tuntia}} {minutes, plural, ...} ✓ Extracted, translated, and the plural forms of each language
The =0 form leaves out "0 hours". The # is the number.
02

Extract: create the resource file and a Soluling project

Install the extract tool with npm install --save-dev @formatjs/cli, and add a script to package.json. For TypeScript, extract from "src/**/*.tsx" instead.

"scripts": {
  "extract": "formatjs extract \"src/**/*.jsx\" --out-file src/translations/en.json"
}

Run npm run extract. It writes the marked strings to src/translations/en.json, your original resource file. Then drag and drop en.json on Soluling. In the Select File Type dialog, select React-Intl resource file: the file is also valid generic JSON, but only this parser understands the descriptions and the message syntax. Add the target languages, and click Finish.

Extracting and creating the project npm run extract writes en.json, which goes through the Select File Type dialog (React-Intl resource file) and Select Languages page (Finnish, German, Japanese). Extract npm run extract src\translations\en.json Select file type React-Intl resource file Languages Finnish (fi) German (de) Japanese (ja) Select React-Intl resource file, not the generic JSON file.
03

Translate: texts, placeholders, and plural patterns

Each extracted string is a row in the grid, with its description as a comment. Placeholders such as {name} are protected: the translator moves them but doesn't change them. Plurals and selects open in the pattern editor, which shows the plural forms that each target language needs, such as one and other in Finnish and only other in Japanese.

  • Machine translation and translation memory. Click Use Machine Translation to translate with Amazon, Claude, DeepL, Google, Microsoft, ModernMT, or MyMemory, and reuse earlier translations from translation memory and terminology.
  • External translators. Send a translation package, an Excel file, or XLIFF to a translator, and import the results back. See teamwork.
  • Translators in a browser. Upload the project to Soluling Cloud and let translators work in Translate.
04

Check: find problems before release

Pseudo translation. Click Translate | Pseudo Translations | Fill, build, and run the application. Pseudo translations are longer and use accented characters, so texts that don't fit and strings still in the code (shown in plain English) stand out. See pseudo translation.

Pseudo-translated build

[Ðŕîvîñĝ Ţîɱé ___] PS Driving distance 220 Driving speed 88 [Çåļçûļåţé ______________] [Çåļçûļåţé ______________] [Ðŕîvîñĝ ţîɱé îš 2 ĥôûŕš 30 ɱîñûţéš ________] Too long and still English (hard-coded)

Validation. Soluling validates translations while you type and in batch (Validation | Validate Translations): missing translations, inconsistent placeholders and patterns, duplicate hotkeys, and more. See validation.

Validation

⚠ Inconsistent format string result (German) The original has {hours} and {minutes}; the translation has only {hours}: Fahrzeit: {hours, plural, one {# Stunde} other {# Stunden}} ⚠ Inconsistent pattern count result (Japanese) Japanese has only the other plural form, but the translation has one and other.
05

Build: create the runtime files and import them

Choose Home | Build All. Soluling writes fi.json, de.json, and ja.json into src/translations. The application imports them and passes the messages of its language to IntlProvider. English is the original language, so it has no file, and React Intl uses the default messages:

// src\main.jsx
import messages_de from './translations/de.json';
import messages_fi from './translations/fi.json';
import messages_ja from './translations/ja.json';

const messages = {
  de: messages_de,
  fi: messages_fi,
  ja: messages_ja,
};

<IntlProvider locale={language} defaultLocale="en" messages={messages[language]}>
  <App language={language} onLanguageChange={changeLanguage} />
</IntlProvider>

Then build the application as usual, with npm run build. Every imported language is in the bundle.

Resource files and the built application src\translations has the extracted en.json and the runtime files fi.json, de.json, and ja.json. npm run build writes one application with every language into the dist folder. Soluling: Build All DIR src\translations\ JSON en.json extracted: with descriptions JSON fi.json runtime: flat, id and value JSON de.json JSON ja.json React: npm run build DIR dist\ DIR index.html and the bundle with every language
06

Update: translate only what changed

When the application changes, run npm run extract again and click Home | Scan. Soluling keeps the existing translations, adds the new strings, and marks the rows whose original text changed. Translate the new rows, build, and build the application. Add the extract, scan, and build steps to your build pipeline with SoluMake or, with Soluling Cloud, SoluCLI.

Reference

The extracted format and the runtime format are different

Both are JSON, but the extracted file has the descriptions and the runtime file is a flat list of IDs and values. You don't convert them: Soluling reads the extracted format, or a runtime file you wrote by hand, and always writes the runtime format.

// en.json, extracted
{
  "drivingTime": {
    "defaultMessage": "Driving Time"
  },
  "result": {
    "defaultMessage": "Driving time is {hours, plural, ...}",
    "description": "hours, minutes: The driving time"
  }
}

// fi.json, written by Soluling
{
  "drivingTime":"Ajoaika",
  "result":"Ajoaika on {hours, plural, ...}"
}

The id connects a translation to its string. React Intl also accepts a text without a defaultMessage, with the text itself as the id, but then the translation no longer matches when you change the text. That is why the Driving sample uses a short id and a defaultMessage.

Fallback

The sample removes the region from the browser's language, so fi-FI uses fi.json. If a string is not translated, or the language has no file, React Intl uses the defaultMessage, the original text in the code.

Message lookup for a browser in fi-FI For a browser in fi-FI, the code removes the region. drivingTime and calculate are found in fi.json as Ajoaika and Laske. A string that was not translated uses its defaultMessage, the original text. UI culture: fi-FI fi-FI region removed by the code fi.json defaultMessage original text in the code drivingTime – ✓ Ajoaika calculate – ✓ Laske aNewString – not translated ✓ A new string

Choose and change the language

The sample starts with the language the user selected earlier, or with the browser's language. It keeps the language in the state of a component around IntlProvider. When the user selects another language, React renders the application again with the new messages, without loading the page again.

// src\main.jsx in the react-intl project
const STORAGE_KEY = 'language';

// The language selected by the user, or the language of the browser without the region code
function getInitialLanguage() {
  return localStorage.getItem(STORAGE_KEY) || (navigator.language || 'en').split(/[-_]/)[0];
}

function Root() {
  const [language, setLanguage] = useState(getInitialLanguage);

  function changeLanguage(value) {
    localStorage.setItem(STORAGE_KEY, value);
    setLanguage(value);
  }

  return (
    <IntlProvider locale={language} defaultLocale="en" messages={messages[language]}>
      <App language={language} onLanguageChange={changeLanguage} />
    </IntlProvider>
  );
}

Other libraries: LinguiJS and i18next

  • LinguiJS: the process is similar, with its own marking and extract tool. See the Samples\React\Lingui\hello sample.
  • i18next and react-i18next: Soluling and Soluling Cloud have an i18next resource file type. See i18next localization and the Samples\React\i18next\sample sample.

Translate in Soluling Cloud

With Soluling Cloud, translators use Translate in a browser. How you start depends on what you localize:

  • React Intl resource files (.json). On the dashboard, add a project, select src/translations/en.json, and choose React-Intl resource file (.json) as the source type. Translators work in Translate; click Build localized files, and save the downloads to src/translations as fi.json and so on. When the application changes, upload the new en.json; the existing translations are kept. No desktop step is needed.

To run the scan, upload, import, and build steps in your build pipeline, use SoluMake. See the Cloud tutorial and workflows.

Do and don't

Do

  • Mark attributes such as title and placeholder with formatMessage.
  • Use formatMessage for every text in code, including the page title.
  • Give each text a short, stable id, with the text in defaultMessage.
  • Describe every placeholder with description.
  • Use ICU plural and select expressions.
  • Pseudo-translate before the first real translation.

Don't

  • Build sentences from pieces in JSX or code.
  • Pass a template literal or a variable as the id; the extract tool can't read it.
  • Choose plural forms with if statements; other languages have other rules.
  • Add en.json as a generic JSON file; you lose the descriptions and the message syntax.
  • Import the extracted en.json as messages; it isn't in the runtime format.

Typical localizability problems

See also internationalization and pseudo translation.

Problem How it shows Find and fix
Unmarked attributes Placeholders and tooltips in English in a pseudo-translated build Use intl.formatMessage for the attribute.
Strings in code Messages and the page title in English Use intl.formatMessage.
Sentences built from pieces Word order and plurals are wrong in the translation Use one message with placeholders, or an ICU plural expression.
Translations lost after a text change Rows come back untranslated after a typo fix Use a short, stable id with defaultMessage.
Fixed widths Clipped text in the pseudo or German build Let the layout grow with the text.

Troubleshooting

Symptom Likely cause What to do
A text is missing from en.json It is not marked, or its id is not a plain string Mark it, use a plain string, and run npm run extract again.
The application stays in English The language's file is not imported, or the locale has a region code Import the file, add it to messages, and remove the region from the language.
Descriptions are missing in Soluling The file was added as a generic JSON file Create the project again with React-Intl resource file.
The console shows missing translation errors The language has no translation for the id Translate the rows and build again; the original text is used until then.
A new string isn't translated after an update en.json wasn't extracted again Run npm run extract, scan, translate, and build.

Samples

The samples are in Samples\React of the Soluling installation and on GitHub:

  • Driving\original: the driving time calculator of this guide before internationalization. Try this first.
  • Driving\react-intl: internationalized with React Intl and localized into Finnish, German, and Japanese, with a language selector and the Soluling project, src\translations\en.ntp.
  • tic: React's Tic-Tac-Toe tutorial, English only (original) and localized (react-intl).
  • sport and sport-ts: applications that use a multilingual API, in JavaScript and TypeScript.
  • Intl\hello, Lingui\hello, and i18next\sample: simple applications for each library.

See React localization in the Desktop documentation for all the details.

FAQ

Soluling supports React Intl, LinguiJS, and i18next. This guide uses React Intl, which uses the ICU message syntax for plurals and selects.

Yes. Upload en.json to Soluling Cloud, translate in Translate, and download the localized files. See Translate in Soluling Cloud.

No. One build holds every language you import, and the application chooses at runtime.

Yes. Keep the language in React state, and render IntlProvider with the messages of the new language. See Choose and change the language.

Yes. Extract from .ts and .tsx files. The sport-ts sample is a TypeScript application.

Related

All guides