reactjsreact-i18next

React + i18next: Why aren't my nested keys working?


I am using ReactJS for a small website. I decided to use i18next for the internationalization and it works - unless I use a nested reference for the translation key.

In the following example the intro1 and intro2 key are displayed, but welcome.headtitle is not found (error "missingKey" in the console).

App.js:

...
 <p><Trans i18nKey='intro1'/></p>
 <p><Trans i18nKey='intro2'/></p>
 <p><Trans i18nKey='welcome.headtitle'/></p>
...

translation.json:

{
  "welcome": {
    "headtitle": ...
    ...
  },
  "intro1": ...,
  "intro2": ...,
}

I know that i18next allows for nested JSON translation objects. What am I doing wrong? I have checked the documentation and examples and didn't notice any error.


Solution

  • while the answer to use "welcome.name" etc is a valid usage, for my use case, I actually needed to use structured keys so that I can better structure my translations.

    What made the nested values work for me was removing the keySeparator: false from the i18n.init function.

    Code would be:

    
    i18n.use(initReactI18next).init({
      resources: {
        en: {translation: EN},
        fr: {translation: FR},
      },
      lng: 'en',
      fallbackLng: 'en',
      // keySeparator: false, // this was the line that I've had to remove to make it work
      // keySeparator: '.', // if you want to re-enable it (not "true", but actual separator value)
      interpolation: {
        escapeValue: false,
      },
    });
    

    and my JSON looks like:

    {
      "nested": {
        "value": "Trying a nested value"
      }
    }
    

    my HTML (div in my react component):

    <div>{t("nested.value")}</div>
    

    If you want to re-enable nested keys, don't use keySeparator: true. You need to specify key separator symbol like this: keySeparator: '.' (thanks @glinda93 for specifying this :) ).