amannn / next-intl

🌐 Internationalization (i18n) for Next.js
https://next-intl-docs.vercel.app
MIT License
2.58k stars 236 forks source link

Add support for returning translated objects and arrays #1434

Closed astralarya closed 3 weeks ago

astralarya commented 4 weeks ago

Is your feature request related to a problem? Please describe.

I would like to be able to retrieve translated objects and arrays. See the feature from i18next: https://www.i18next.com/translation-function/objects-and-arrays

Describe the solution you'd like

Perhaps the t object could have a .object() function. For example:

en.json

{
  "MyScope": {
    "MyObject": [
      {
        "label": "Label 1",
        "value": "Value 1"
      },
      {
        "label": "Label 2",
        "value": "Value 2"
      }
    ]
  }
}

component.tsx

function MyObject() {
  const t = useTranslations("MyScope");
  const myObject = t.object("MyObject");
  return <dl>
    {myObject.map((item, idx) => (
      <Fragment key={idx}>
        <dt>{item.label}</dt>
        <dd>{item.value}</dd>
      </Fragment>
    ))}
  </dl>
}

Describe alternatives you've considered

The simple example above could be done with .rich() or .markup(), but imagine instead of a simple <dl> list, we are passing props to components, etc. There is also the useMessages() hook, but that is extremely manual and way less convenient than having a .object() function which could do it automatically.

amannn commented 3 weeks ago

Handling arrays is covered in the docs, please have a look: Arrays of messages