2

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.

1 Answer 1

2

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>
)
Sign up to request clarification or add additional context in comments.

4 Comments

I just edited my question and provide full code and error message, thanks.
Is there a particular reason for you to do it with an array inside of "items"? Otherwise I'd recommend structuring you json like this solution form github. It's going to be much easier to get a specific item like this and you can still make a loop later on if needed
I just want to conveniently loop when needed and maintain my commonly used format. I found that the message method of array object is not mentioned in the doc. Is this not recommended by next-intl? thanks.
I t's not recommended no, at least as far as I know. I changed my answer to show what I think is the best solution for you, hope that helps

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.