Search code examples
reactjsjsontranslatei18next

How to get an iterateable js array from translation.json


I'm using react-i18next.

import * as i18next from 'react-i18next';
export const translate:t = i18next.useTranslation(); // no doubt for this because it works for flat object like users.count (which displays 2 as expected)

translation.json from public/locales/en

{
    "users" : {
        "typeA": [
            { "name": "John", "address": "addressofjohn" },
            { "name": "John", "address": "addressofjohn" }
        ],
        "count": 2
    }
}

And I pass this typeA array to my component.

<Component user={translate("users.typeA")} />

In my component, when I log that, it displays like below, I can't loop through it.

"key 'users.typeA (en-US)' returned an object

Tries:

<Component user={Array.from(translate("users.typeA")} />
<Component user={JSON.parse(translate("users.typeA")} />

Solution

  • Simple way as in the documentation:

    <Component user={translate("users.typeA", {returnObjects: true})} />