Sub topic 7
Plural forms across languages
This chapter assumes you have react-i18next set up with a catalog and useTranslation working, as in the earlier chapters. It also assumes you can read TypeScript and run a script in Node 18 or later.
Why `count === 1 ? 'item' : 'items'` fails
English has two plural forms: "1 item" and "2 items". Many developers write the check by hand:
<p>{count} item{count === 1 ? '' : 's'}</p>This breaks in three ways:
- The sentence is built from fragments, so a translator cannot reorder or replace the words.
- The rule "one versus everything else" is English-specific. Russian, Arabic, Polish and others use different rules.
- The word ending is hard-coded, so languages that change the whole noun cannot use it.
The fix is to store every plural form as a separate message and let a rule choose one, based on the number and the active locale.
CLDR plural categories
The Unicode CLDR project defines up to six plural categories. Each language uses a subset of them.
| Category | Meaning | Example |
|---|---|---|
| `zero` | Languages with a special form for zero | Arabic: 0 |
| `one` | The singular-like form | English: 1. Russian: 1, 21, 31 |
| `two` | A dual form | Arabic: 2 |
| `few` | A small group | Russian: 2 to 4, 22 to 24. Arabic: 3 to 10 |
| `many` | A larger group | Russian: 0, 5 to 20, 25 to 30. Arabic: 11 to 99 |
| `other` | Everything else, and the catch-all | Every language |
The category names are labels for rules. They do not literally mean "one" or "many". In French, one covers both 0 and 1. In Russian, 21 is one and 11 is many. Japanese and Chinese have only other, so a single message covers every count.
Every language has other. Keep that in mind later when we talk about fallbacks.
Asking the browser which category applies
Intl.PluralRules implements the CLDR rules. You pass a number and it returns a category name.
const ru = new Intl.PluralRules('ru');
const ar = new Intl.PluralRules('ar');
const ja = new Intl.PluralRules('ja');
for (const n of [0, 1, 2, 5, 11, 21, 22, 1.5]) {
console.log(`ru ${n}: ${ru.select(n)}`);
}
for (const n of [0, 1, 2, 3, 11, 100]) {
console.log(`ar ${n}: ${ar.select(n)}`);
}
console.log(`ja 1: ${ja.select(1)}`);
console.log(`resolved categories for ru: ${ru.resolvedOptions().pluralCategories.join(', ')}`);The Russian results are many for 0, one for 1, few for 2, many for 5 and 11, one for 21, few for 22, and other for 1.5. Arabic gives zero, one, two, few, many, other for 0, 1, 2, 3, 11 and 100. Japanese gives other.
resolvedOptions().pluralCategories lists the categories a locale actually uses. Use it to decide how many translations a language needs.
Plural keys in i18next
i18next uses the same Intl.PluralRules data. It looks for a key with the category as a suffix. Since i18next v21 (JSON format v4), the suffixes are _zero, _one, _two, _few, _many and _other. Older tutorials show _plural, which only fits two-form languages. Avoid it in new code.
Mermaid diagrams must use the diagram fence defined for this platform, so here is the lookup flow in that form:
Here is a catalog with English and Russian plurals:
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
const resources = {
en: {
translation: {
messages_one: 'You have {{count}} new message',
messages_other: 'You have {{count}} new messages',
},
},
ru: {
translation: {
messages_one: 'У вас {{count}} новое сообщение',
messages_few: 'У вас {{count}} новых сообщения',
messages_many: 'У вас {{count}} новых сообщений',
messages_other: 'У вас {{count}} новых сообщения',
},
},
};
i18n.use(initReactI18next).init({
resources,
lng: 'ru',
fallbackLng: 'en',
interpolation: { escapeValue: false },
});
export default i18n;The call site stays the same for every language:
import { useTranslation } from 'react-i18next';
export function Inbox({ unread }: { unread: number }) {
const { t } = useTranslation();
return <p>{t('messages', { count: unread })}</p>;
}Note that the code passes the base key messages, not messages_one. The option name must be exactly count. The same count fills the {{count}} placeholder, so you do not pass it twice.
The Russian other form is used for fractions such as 1.5 ("1,5 нового сообщения" in natural speech, grammatically a genitive singular). Translators need an other entry even when the whole-number categories feel complete.
Common errors
Missing categories
If Russian has messages_one and messages_other but no messages_few, a count of 3 falls back to messages_other. Nothing crashes, but the grammar may be wrong. Give translators every category a language needs. You can list them with new Intl.PluralRules('ru').resolvedOptions().pluralCategories.
A count that is a string
t('messages', { count: '3' }) may not select the right form in every setup. Convert values from inputs or URLs with Number(...) before you pass them.
Treating zero as a plural category
In English, 0 belongs to other, so the result is "0 messages". If you want "No new messages", add a message for zero. Recent i18next versions look for messages_zero when count is 0 and that key exists. Check your installed version's documentation, and test it. A portable alternative is a separate key:
{unread === 0 ? t('messages_empty') : t('messages', { count: unread })}Reusing one plural message for two nouns
"1 file selected" and "1 folder selected" need separate keys, because other languages inflect the noun and the verb. Do not build "selected" as a suffix.
Splitting numbers from words
Do not write {count} {t('item', { count })}. The number may need to come after the noun in some languages, and the number itself needs locale formatting. Keep the count inside the message.
Formatting the number inside a plural message
For a large count, "1234 items" in English becomes "1.234 Artikel" in German. i18next can format interpolated values with the Intl formatters, so the plural category and the number format both follow the locale:
import i18n from 'i18next';
i18n.init({
lng: 'de',
resources: {
de: {
translation: {
items_one: '{{count, number}} Artikel',
items_other: '{{count, number}} Artikel',
},
},
},
});
console.log(i18n.t('items', { count: 1234 })); // 1.234 ArtikelThe number format uses Intl.NumberFormat with the active language. The plural category is still chosen from the raw count, so formatting does not change which message is used.
Ordinals: 1st, 2nd, 3rd
Ordinal numbers follow different rules from cardinal counts. English has one (1st, 21st), two (2nd, 22nd), few (3rd, 23rd) and other (4th, 11th). Ask Intl.PluralRules for them with type: 'ordinal':
const ordinal = new Intl.PluralRules('en', { type: 'ordinal' });
const suffixes: Record<string, string> = { one: 'st', two: 'nd', few: 'rd', other: 'th' };
function withSuffix(n: number): string {
return `${n}${suffixes[ordinal.select(n)]}`;
}
console.log([1, 2, 3, 4, 11, 12, 13, 21, 22, 23].map(withSuffix).join(' '));
// 1st 2nd 3rd 4th 11th 12th 13th rdIn i18next, ordinal keys include _ordinal_ before the category, forordinalone, and you call t('place', { count: 3, ordinal: true })`.
Checking your catalogs
A short script can find missing categories before translators or users do. It compares the plural keys in a catalog with what each locale needs:
const catalog: Record<string, Record<string, string>> = {
en: { messages_one: 'a', messages_other: 'b' },
ru: { messages_one: 'a', messages_other: 'b' },
};
for (const [locale, messages] of Object.entries(catalog)) {
const needed = new Intl.PluralRules(locale).resolvedOptions().pluralCategories;
const missing = needed.filter((c) => !('messages_' + c in messages));
if (missing.length > 0) {
console.log(`${locale} is missing: ${missing.join(', ')}`);
}
}The script prints ru is missing: few, many. Run something like it in CI for every plural base key.
Summary of the working model
- CLDR defines up to six plural categories, and each language uses its own subset and its own rules.
Intl.PluralRulesmaps a number to a category for a locale.- i18next appends the category to your key and falls back to
_other. - Pass a numeric
count, and keep the number inside the message. - Handle "zero" and ordinals explicitly.
Exercise
A catalog for Polish contains files_one and files_other. A user has 3 files, and t('files', { count: 3 }) shows the files_other text. Why is this a problem, and how do you find out which keys Polish needs?
Show answer
Polish distinguishes one, few, many and other, and 3 belongs to few. With no files_few key, i18next silently falls back to files_other, which may be grammatically wrong. Call new Intl.PluralRules('pl').resolvedOptions().pluralCategories to list the needed categories, then add files_few and files_many with translations.
Exercise
What does new Intl.PluralRules('en', { type: 'ordinal' }).select(22) return, and what suffix does it map to in English?
Show answer
It returns two, which maps to "nd" ("22nd").