Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 934
Faire Avatar asked Aug 28 '19 11:08

Faire


1 Answers

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
  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>
like image 140
Sanda Avatar answered Oct 08 '22 15:10

Sanda