patternjavascriptTip
react-intl FormatMessage: Translating Strings in React
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 — useintl.formatMessageif 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
createIntlfor non-React contexts.
Revisions (0)
No revisions yet.