Sub topic 6
Variables in Messages Instead of String Concatenation
This chapter assumes you have react-i18next set up from the earlier chapters. That means an i18n instance with a catalog, and components that call t from useTranslation. You should be comfortable with TypeScript and with the shape of a message catalog.
Why concatenation breaks
The first instinct when a sentence contains a dynamic value is to join pieces together:
// Do not do this
<p>{t('added_prefix')} {item} {t('added_middle')} {list}</p>This hard-codes the English word order into your component. It also splits one sentence into fragments, and a translator sees only the fragments, without the sentence around them. Take the English message "Mina added Notebook to Wishlist". In Japanese the list comes before the item, and the verb comes last: 「Minaさんが Wishlist に Notebook を追加しました」. Fragments joined in code cannot produce that order. Translators also cannot adjust the grammar around a value, such as particles, case endings, or spacing.
The fix is one complete sentence per key, with named placeholders where the values go. The translator moves the placeholders to wherever the target language needs them.
Placeholders in the catalog
i18next marks a placeholder with double curly braces: {{name}}. The placeholder name is a key in the options object you pass to t.
import i18next from 'i18next';
async function main() {
const i18n = i18next.createInstance();
await i18n.init({
lng: 'en',
fallbackLng: 'en',
resources: {
en: { translation: { added: '{{user}} added {{item}} to {{list}}.' } },
ja: { translation: { added: '{{user}}さんが{{list}}に{{item}}を追加しました。' } },
},
interpolation: { escapeValue: false },
});
const values = { user: 'Mina', item: 'Notebook', list: 'Wishlist' };
console.log(i18n.t('added', values));
console.log(i18n.t('added', { ...values, lng: 'ja' }));
}
main();This prints:
Mina added Notebook to Wishlist.
Minaさんが Wishlistに Notebookを追加しました。The calling code is identical for both languages. Only the catalogs differ. The lng option overrides the active language for a single call. Day to day you rely on the language set by changeLanguage, as covered in the locale switching chapter.
In a component, the call looks the same:
import { useTranslation } from 'react-i18next';
export function ActivityItem(props: { user: string; item: string; list: string }) {
const { t } = useTranslation();
return <p>{t('added', props)}</p>;
}Escaping and why we turn it off
By default i18next escapes HTML characters in interpolated values. A value of Tom & Jerry becomes Tom & Jerry. This protects code that inserts the string as raw HTML.
React already escapes text it renders. If both layers escape, the user sees the literal text &. That is why the setup chapter sets escapeValue: false.
Turning it off is safe only while the output stays in React text or attribute positions. The string from t becomes unsafe if you pass it to dangerouslySetInnerHTML, or to any API that parses HTML. In those places, leave escapeValue on for that call:
import i18next from 'i18next';
async function main() {
const i18n = i18next.createInstance();
await i18n.init({
lng: 'en',
resources: { en: { translation: { who: 'By {{name}}', whoRaw: 'By {{- name}}' } } },
// escapeValue defaults to true here
});
console.log(i18n.t('who', { name: 'Tom & <b>Jerry</b>' }));
console.log(i18n.t('whoRaw', { name: 'Tom & <b>Jerry</b>' }));
}
main();The first call prints By Tom & <b>Jerry</b>. The second call uses {{- name}}, which skips escaping for that one placeholder, and prints the value unchanged. Use that form rarely, and only for values you trust.
Naming placeholders
Translators read your placeholder names, so choose names that say what the value is. {{user}} and {{list}} are clear. {{0}} and {{x}} are not. Names also work as documentation when someone changes a message months later.
Some names are reserved because i18next reads them as options, not as values. Avoid count, context, lng, ns, defaultValue, replace, and returnObjects as ordinary placeholders. count is special on purpose. It selects the plural form, and the next chapter covers it.
Placeholders can read nested values with dot notation:
i18n.t('profile', { user: { name: 'Mina', city: 'Osaka' } });
// catalog: "profile": "{{user.name}} lives in {{user.city}}."Pass only what the message needs. Handing a whole object to t makes it harder to see which fields the translators may use.
Formatting values inside a message
A number or currency also needs locale-aware formatting, and placeholders can do that. Since i18next 21.3, a placeholder can name a formatter after a comma, and the formatter uses the Intl APIs and the active language:
import i18next from 'i18next';
async function main() {
const i18n = i18next.createInstance();
await i18n.init({
lng: 'en',
resources: {
en: { translation: { total: 'Total: {{amount, currency(EUR)}}' } },
de: { translation: { total: 'Gesamt: {{amount, currency(EUR)}}' } },
},
});
console.log(i18n.t('total', { amount: 1234.5 }));
console.log(i18n.t('total', { amount: 1234.5, lng: 'de' }));
}
main();The output is Total: €1,234.50 and Gesamt: 1.234,50 €. The German result contains a non-breaking space between the number and the euro sign. The amount stays a plain number in your code. The message decides how to present it, and the translator can change the formatter if a language needs a different style.
The earlier Intl.NumberFormat approach still works, and it suits cases where you format a value outside any message. Pick one approach per value so you do not format twice. Formatting a number into a string and then passing that string to a currency placeholder gives wrong output.
When a value is missing
If you forget a value, the placeholder is not replaced. In current i18next versions the user sees the literal text {{item}} in the page. Nothing throws. This makes missing values easy to overlook in manual testing.
You can catch them during development with missingInterpolationHandler:
i18n.init({
// ...
interpolation: {
escapeValue: false,
missingInterpolationHandler(text: string, match: RegExpExecArray) {
console.error(`Missing value for ${match[1]} in "${text}"`);
return `[${match[1]}]`;
},
},
});The handler receives the original text and the regex match. The returned string replaces the placeholder. The testing chapter returns to this idea of failing loudly in a test run.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Joining several `t()` results with JSX text | Wrong word order, untranslatable grammar | One key per sentence, with placeholders |
| Leaving `escapeValue` on in React | `&` and `'` appear on screen | Set `escapeValue: false` |
| Misspelling a placeholder name in the options | `{{usre}}` shows in the UI | Match names exactly, add a missing-value handler |
| Using `count` as a general variable | The plural lookup runs and the key is not found | Use another name unless you want a plural |
| Pre-formatting a number, then using a formatter on it | Wrong or `NaN` output | Pass the raw number |
| Placing translated output in raw HTML | Script injection risk | Keep escaping on for that call, or avoid raw HTML |
Exercise
The German catalog has "greet": "Hallo, {{name}}!" but a component calls t('greet', { username }). What does the user see, and how would you detect the mistake during development?
Show answer
The user sees Hallo, {{name}}! because no value named name was passed, and no error is thrown. Detect it by setting missingInterpolationHandler in the i18next options so it logs or throws in development, or by covering the component with a test that asserts the rendered text contains no {{.
Exercise
Rewrite <p>{t('you_have')} {count} {t('new_messages')}, {name}</p> as one message. Give the English and German catalog entries and the call. Ignore plural forms for now, and use total for the number so the plural lookup is not triggered.
Show answer
Catalog en: "inbox": "{{name}}, you have {{total}} new messages." Catalog de: "inbox": "{{name}}, Sie haben {{total}} neue Nachrichten." Call: <p>{t('inbox', { name, total })}</p>. Each language keeps its own word order inside a single key, and the component code does not change between languages.