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?

4

2 Answers 2

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"

Sign up to request clarification or add additional context in comments.

Comments

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); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.