I\'m trying to use react-intl
package inside an app. The app is rendered on the server so I wrote some code to determine which language to use and serve into
Yes, customization using flattenMessages is the best way I found.
Here is the video demo for your reference.
https://egghead.io/lessons/react-convert-a-hard-coded-string-using-react-intl-formattedmessage
Since React Intl v2 no longer supports nested messages objects, the messages need to be flattening.
export const flattenMessages = ((nestedMessages, prefix = '') => {
if (nestedMessages === null) {
return {}
}
return Object.keys(nestedMessages).reduce((messages, key) => {
const value = nestedMessages[key]
const prefixedKey = prefix ? `${prefix}.${key}` : key
if (typeof value === 'string') {
Object.assign(messages, { [prefixedKey]: value })
} else {
Object.assign(messages, flattenMessages(value, prefixedKey))
}
return messages
}, {})
})
// Use flattenMessages
<IntlProvider locale={locale} messages={flattenMessages(messagesForLocale)}>
refs:
react-intl
does not support nested messages anymore. If you still want to organize your messages that way, you can use the flat
library to correct your messages structure beforehand.
import flatten from 'flat'
<IntlProvider locale={locale} messages={flatten(messagesForLocale)}>
https://github.com/hughsk/flat