23

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.

Faire
  • 706
  • 1
  • 9
  • 31

1 Answers1

56

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 :) ).

Sanda
  • 1,357
  • 19
  • 29
  • 13
    FYI, if you want to reenable nested keys, don't use `keySeparator: true`. You need to specify key separator symbol like this: `keySeparator: '.'` – glinda93 Aug 20 '20 at 12:54
  • thanks, this fixed it and in my opinion i think this should be a stand-alone answer, not a comment so that the users can see it better – besim Jan 10 '23 at 23:35
  • Many thanks @glinda93. Have added the correction as suggested :) . – Sanda Jan 11 '23 at 14:54