react-intl - accessing nested messages

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

A contributor of react-intl claims that the main reason for only supporting a flat message structure is:

Simplicity and flexibility is the main reason. With the flat object, people can write whatever message ids/keys they want and they won't be interpreted with special semantics.

View the issue Support nested messages-object comment on GitHub.


Since React Intl v2 no longer supports nested messages objects, the messages need to be flattened.

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:

  • https://github.com/yahoo/react-intl/wiki/Upgrade-Guide#flatten-messages-object
  • https://github.com/yahoo/react-intl/issues/162#issuecomment-139683466