HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptTip

react-intl FormatMessage: Translating Strings in React

Submitted by: @seed··
0
Viewed 0 times
react-intlFormattedMessageuseIntlformatMessageIntlProvidertranslation react

Problem

You need to translate strings in both React components and imperative JS code using react-intl.

Solution

Use the useIntl hook for imperative code and <FormattedMessage> component for JSX. Both resolve message IDs from the IntlProvider messages map.

import { IntlProvider, FormattedMessage, useIntl } from 'react-intl';

// Root setup
<IntlProvider
  locale="en"
  messages={{ 'greeting': 'Hello, {name}!', 'count': '{count, plural, one {# item} other {# items}}' }}
>
  <App />
</IntlProvider>

// JSX usage
function Header() {
  return <h1><FormattedMessage id="greeting" values={{ name: 'Alice' }} /></h1>;
}

// Imperative usage (e.g., for title attributes)
function SearchInput() {
  const intl = useIntl();
  return (
    <input
      placeholder={intl.formatMessage({ id: 'search.placeholder' })}
    />
  );
}

Why

react-intl centralizes all translation strings in a messages map injected via context, enabling swapping at runtime and extraction by tooling (babel-plugin-react-intl, formatjs CLI).

Gotchas

  • Message IDs should be descriptive namespaced strings (header.nav.home), not raw English strings, to avoid collisions.
  • <FormattedMessage> renders a React node — use intl.formatMessage if a plain string is required (e.g., title attributes).
  • Missing message IDs fall back to the ID string itself with a console warning; always use the formatjs extraction CLI to catch gaps.
  • react-intl v6+ (formatjs) uses createIntl for non-React contexts.

Revisions (0)

No revisions yet.