React › Internationalization (i18n) in React

How do you handle pluralization correctly across different languages in an internationalized React app?

Advanced

Answer

Different languages have very different rules for plurals, some with more than just a singular and plural form. Translation libraries like react i18next let you define separate translations for different count ranges, and automatically pick the correct one based on both the language and the actual number being displayed.
// translation file
{
  "item_one": "You have {{count}} item",
  "item_other": "You have {{count}} items"
}

function CartCount({ count }) {
  const { t } = useTranslation();
  return <p>{t('item', { count })}</p>;
}
Real-world example A shopping cart correctly shows You have 1 item versus You have 3 items in English, and automatically shows the correct grammatically different forms in a language like Polish that has more complex plural rules.

Common follow-ups: Why do some languages need more than two plural forms while English only needs two?;How would you test that pluralization works correctly for every supported language?