1

I use react-intl in my project and I load json files for any language but I need my json file have a tree format. When I load my component react-intl printing the key string of json. For example:

{ 
 "header":{
  "title": "My title",
  "text": "My text"
 },
 "footer":{
  "title": "My title",
  "text": "My text"
 } 
}

When I use:

<p><FormattedMessage id="header.title"/></p>

the result is: <p>header.title</p>

Any idea?

Aditi Parikh
  • 1,522
  • 3
  • 13
  • 34
Toni Chaz
  • 651
  • 11
  • 22
  • post your app.js file – Shota Oct 03 '16 at 14:44
  • At the moment i find **Flatten messages Object** in the react-intl [doc](https://github.com/yahoo/react-intl/wiki/Upgrade-Guide#flatten-messages-object) Thanks @Shota – Toni Chaz Oct 03 '16 at 18:29
  • Please find my answer from here. [https://stackoverflow.com/a/50810710/1230432](https://stackoverflow.com/a/50810710/1230432) – Krupal Patel Jun 13 '18 at 03:24
  • Does this answer your question? [react-intl - accessing nested messages](https://stackoverflow.com/questions/45783677/react-intl-accessing-nested-messages) – banan3'14 Nov 16 '21 at 09:23

2 Answers2

1

I find the Flatten messages Object of official doc

function flattenMessages(nestedMessages, prefix = '') {
 return Object.keys(nestedMessages).reduce((messages, key) => {
    let value       = nestedMessages[key];
    let prefixedKey = prefix ? `${prefix}.${key}` : key;

    if (typeof value === 'string') {
        messages[prefixedKey] = value;
    } else {
        Object.assign(messages, flattenMessages(value, prefixedKey));
    }

    return messages;
 }, {});
}

let messages = flattenMessages(nestedMessages);
Toni Chaz
  • 651
  • 11
  • 22
1

If you want to do this without "Flatten messages Object", you can use FormattedMessage like this:

<FormattedMessage id="header">
  {txt => <span>{txt[title]}</span>}
</FormattedMessage>

Result will be: "My title"

or of course:

<FormattedMessage id="footer">
  {txt => <span>{txt[text]}</span>}
</FormattedMessage>

Result will be: "My Text"