Reputation: 751
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?
Upvotes: 1
Views: 3901
Reputation: 44
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"
Upvotes: 1
Reputation: 751
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);
Upvotes: 1