Learn plural forms in i18next

I’m having trouble getting i18next to work with react-i18next and i18next-parser.

In my source code, I have something like:

<p>{t('{{count}} Sensors', { count: getSensorCount() })}</p>

where getSensorCount() returns a number.

My i18next-parser config is as follows:

  locales: ['en', 'fr', 'es'],
  output: 'src/locales/$LOCALE/$NAMESPACE.json',
  defaultValue: (locale, namespace, key, value) => value || key,
  keySeparator: false,
  namespaceSeparator: false,
  verbose: true,
  createOldCatalogs: false

Running the parser generates a JSON file with the keys like:

  "{{count}} Sensors_one": "{{count}} Sensors",
  "{{count}} Sensors_other": "{{count}} Sensors",

I expect this to return “1 Sensor” when count is 1. This is also how the i18next documentation describes plurals to work.

However, it just returns the key, and it seems like it is unable to find the translation in the JSON file.

The only way I can get it to return the proper value is if I change the keys like this:

  "{{count}} Sensors": "{{count}} Sensor",
  "{{count}} Sensors_plural": "{{count}} Sensors",

I’m trying to understand the proper syntax for plural keys and how to configure my project to recognize it. My package versions are:

"i18next": "^20.6.1",
"i18next-parser": "^8.0.0",
"react-i18next": "^13.0.0",
"react": "^18.2.0",

A Codesandbox example of my project is available.

Can someone please help me determine the proper syntax for plural keys and how to configure my project and parser accordingly?

The issue you are facing is related to the syntax and configuration of plural keys in i18next.

To properly configure your project and parser for plural keys, you need to use the correct syntax for plurals in your translation keys. Instead of using {{count}} Sensors_one and {{count}} Sensors_other, you should use {{count}} Sensor_one and {{count}} Sensor_other.

Here’s the modified JSON file with the correct plural key syntax:

  "{{count}} Sensor_one": "{{count}} Sensor",
  "{{count}} Sensor_other": "{{count}} Sensors"

To configure the i18next-parser to recognize plurals, you need to set the pluralSeparator option in your config file. Add the following line to your i18next-parser config:

pluralSeparator: '_'

After making these changes, run the parser again and it should generate the correct JSON file with the plurals recognized.

Note: It’s important to ensure that the syntax for plural keys matches the pluralization rules of the language you are translating into. The example above assumes English language pluralization rules.

Hope this helps!