My message/en.json looks like this
{
"items": [{
"name: "item 1",
"price: "100",
}, {
"name: "item 2",
"price: "200",
}]
}
My page.tsx
import { useTranslations } from 'next-intl';
export default function ProductSection() {
const t = useTranslations() as any;
return <>{t('items[0].price')}</>;
}
Also tried
import { useTranslations } from 'next-intl';
export default function ProductSection() {
const t = useTranslations('items') as any;
return <>{t('[0].price')}</>;
}
I tried above method but get the error message:
IntlError: MISSING_MESSAGE: Could not resolve `items[0].price` in messages for locale `en`.
There is a method on the Internet to map the array object and then loop, but it is not what I want. I don’t need to loop for the time being, I just need to get the item I need.
Here's how you can loop through and array and get the messages you need github:
{
"items": {
"item-1": {
"title": "Item 1",
"value": "34"
},
"item-2": {
"title": "Item 2",
"value": "1000"
},
"item-3": {
"title": "Item 3",
"value": "10000"
},
"item-4": {
"title": "Item 4",
"value": "100"
},
"item-5": {
"title": "Item 5",
"value": "5"
}
}
}
And you can create an array with the different keys:
[
'item-1',
'item-2',
'item-3',
'item-4',
'item-5'
].map((key) =>
<p key={key}>{t(`items.${key}.title`)} ({t(`items.${key}.value`)})</p>
)