Search code examples
arraysjsonreactjsi18nextreact-i18next

Returning a JSON array of translated content using i18n


Context: I am making a multi-language page using the react-i18next module of ReactJS.

Issue: I cannot access the arrayed JSON content.

The translated content being stored in separate JSON files for each language, non-array content works fine and gets correctly displayed and translated, however, I can't seem to use the arrayed content on my React components, let alone access its content through console.log().

Below is an example of my translationEN.json file:

{
  "name": "Test",
  "occupations":["occupation1",
  "Part-time occupation2",
  "Language enthusiast"]
}

I am being able to refer to the non-array name using i18n.t("name"). However, attempting to access my arrayed occupations using i18n.t("occupations") results in the following console.log:

key 'occupations (en)' returned an object instead of string.

Using JSON.stringify() doesn't solve the issue, neither does console.log(i18n.t("occupations"), { returnObjects: true }) as suggested on i18next's documentation

Thanks in advance!


Solution

  • Problem solved. The array values can be accessed as such: i18n.t("occupations.0") for occupation 1, i18n.t("occupations.1") for Part-time occupation 2 and i18n.t("occupations.2") for Language enthusiast. I just need to loop it out to make it look cleaner.