1

The project I'm currently working uses react-intl to handle the i18n and I noticed that components are fed with the formatted message in 3 different ways:

  1. Using a component: <FormattedMessage id="MessageId" />
  2. Using a function: intl.formatMessage({id: "MessageId"})
  3. Directly using the messages object: intl.messages["MessageId"]

I think approach #1 and #2 are the way to go but I think #3 is very limiting.

What are some good reasons to use #3?

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230
Francesco Meli
  • 2,484
  • 2
  • 21
  • 52

1 Answers1

1

The first approach is the react way and is recommended if you are using ReactJS. The FormattedMessage component uses useIntl hook to access the intl object internally (approach #2):

<FormattedMessage id="GREETING" />

The second approach uses the intl object directly without the React abstraction. Use this if you are integrating the intl API with other unsupported frameworks.

intl.formatMessage({ id: "GREETING" })

Don't ever use the third approach. intl.messages is just a normal Javascript object that maps each MessageId to the translated text. You can't even use the ICU Message Formatting. For example:

{
  "GREETING": "Hello, {name}"
}
intl.formatMessage({ id: "GREETING" }, { name: "Near" }); // Hello, Near
intl.messages["GREETING"]; // Hello, {name}
NearHuscarl
  • 66,950
  • 18
  • 261
  • 230