Components
React Intl has a set of React components that provide a declarative way to setup an i18n context and format dates, numbers, and strings for display in a web UI. The components render React elements by building on React Intl's imperative API.
#
Why Components?Beyond providing an idiomatic-React way of integrating internationalization into a React app, and the <Formatted*>
components have benefits over always using the imperative API directly:
- Render React elements that seamlessly compose with other React components.
- Support rich-text string/message formatting in
<FormattedMessage>
. - Implement advanced features like
<FormattedRelativeTime>
's updating over time. - Provide TypeScript type definitions.
#
IntlProviderReact Intl uses the provider pattern to scope an i18n context to a tree of components. This allows configuration like the current locale and set of translated strings/messages to be provided at the root of a component tree and made available to the <Formatted*>
components. This is the same concept as what Flux frameworks like Redux use to provide access to a store within a component tree.
caution
All apps using React Intl must use the <IntlProvider>
or <RawIntlProvider>
component.
This component is used to setup the i18n context for a tree. Usually, this component will wrap an app's root component so that the entire app will be within the configured i18n context. The following are the i18n configuration props that can be set:
#
locale, formats, and messagesThe user's current locale and what the app should be rendered in. While defaultLocale
and defaultFormats
are for fallbacks or during development and represent the app's default. Notice how there is no defaultMessages
, that's because each Message Descriptor provides a defaultMessage
.
#
defaultLocale and defaultFormatsDefault locale & formats for when a message is not translated (missing from messages
). defaultLocale
should be the locale that defaultMessage
s are declared in so that a sentence is coherent in a single locale. Without defaultLocale
and/or if it's set incorrectly, you might run into scenario where a sentence is in English but embeded date/time is in Spanish.
#
textComponentProvides a way to configure the default wrapper for React Intl's <Formatted*>
components. If not specified, <React.Fragment>
is used. Before V3, span
was used instead; check the migration guide for more info.
#
onErrorAllows the user to provide a custom error handler. By default, error messages are logged using console.error
if NODE_ENV
is not set to production
.
#
wrapRichTextChunksInFragmentWhen formatting rich text message, the output we produced is of type Array<string | React.ReactElement>
, which will trigger key error. This wraps the output in a single React.Fragment
to suppress that.
#
defaultRichTextElementsA map of tag to rich text formatting function. This is meant to provide a centralized way to format common tags such as <b>
, <p>
... or enforcing certain Design System in the codebase (e.g standardized <a>
or <button>
...). See https://github.com/formatjs/formatjs/issues/1752 for more context.
These configuration props are combined with the <IntlProvider>
's component-specific props:
Props:
Finally, child elements must be supplied to <IntlProvider>
.
Example:
Assuming navigator.language
is "fr"
:
#
RawIntlProviderThis is the underlying React.Context.Provider
object that IntlProvider
use. It can be used in conjunction with createIntl
:
#
Dynamic Language SelectionBy default, changes to the locale
at runtime may not trigger a re-render of child elements. To solve this, and enable dynamic locale modification, add a key
property to the <IntlProvider>
and set it to the locale, which persuades React that the component has been modified:
(See Issue #243.)
#
FormattedDateThis component uses the formatDate
and Intl.DateTimeFormat
APIs and has props
that correspond to the DateTimeFormatOptions
specified above.
Props:
By default <FormattedDate>
will render the formatted date into a <React.Fragment>
. If you need to customize rendering, you can either wrap it with another React element (recommended), or pass a function as the child.
Example:
Example with Options:
#
FormattedDatePartsbrowser support
This requires Intl.DateTimeFormat.prototype.formatToParts which is not available in IE11. Please use our polyfill if you plan to support IE11.
This component provides more customization to FormattedDate
by allowing children function to have access to underlying parts of the formatted date. The available parts are listed here
Props:
#
FormattedTimeThis component uses the formatTime
and Intl.DateTimeFormat
APIs and has props
that correspond to the DateTimeFormatOptions
specified above, with the following defaults:
Props:
By default <FormattedTime>
will render the formatted time into a React.Fragment
. If you need to customize rendering, you can either wrap it with another React element (recommended), or pass a function as the child.
Example:
#
FormattedTimePartsbrowser support
This requires Intl.DateTimeFormat.prototype.formatToParts which is not available in IE11. Please use our polyfill if you plan to support IE11.
This component provides more customization to FormattedTime
by allowing children function to have access to underlying parts of the formatted date. The available parts are listed here
Props:
#
FormattedDateTimeRangebrowser support
This requires stage-3 API Intl.RelativeTimeFormat.prototype.formatRange which has limited browser support. Please use our polyfill if you plan to support them.
This component uses the formatDateTimeRange
and Intl.DateTimeFormat
APIs and has props
that correspond to the DateTimeFormatOptions
specified above
Props:
By default <FormattedDateTimeRange>
will render the formatted time into a React.Fragment
. If you need to customize rendering, you can either wrap it with another React element (recommended), or pass a function as the child.
Example:
#
FormattedRelativeTimebrowser support
This requires Intl.RelativeTimeFormat which has limited browser support. Please use our polyfill if you plan to support them.
This component uses the formatRelativeTime
API and has props
that correspond to the following relative formatting options:
Prop Types:
By default <FormattedRelativeTime>
will render the formatted relative time into a React.Fragment
. If you need to customize rendering, you can either wrap it with another React element (recommended), or pass a function as the child.
Example:
maximum interval
You can adjust the maximum interval that the component will re-render by setting the updateIntervalInSeconds
. A falsy value will turn off auto-updating. The updating is smart and will schedule the next update for the next interesting moment.
An interesting moment is defined as the next non-fractional value
for that unit
. For example:
This will initially renders 59 seconds ago
, after 1 second, will render 1 minute ago
, and will not re-render until a full minute goes by, it'll render 2 minutes ago
. It will not try to render 1.2 minutes ago
.
limitation
updateIntervalInSeconds
cannot be enabled for unit
longer than hour
(so not for day
, week
, quarter
, year
). This is primarily because it doesn't make sense to schedule a timeout in day
s, and the number of ms
in a day is larger than the max timeout that setTimeout
accepts.
#
FormattedNumberThis component uses the formatNumber
and Intl.NumberFormat
APIs and has props
that correspond to Intl.NumberFormatOptions
.
Props:
By default <FormattedNumber>
will render the formatted number into a React.Fragment
. If you need to customize rendering, you can either wrap it with another React element (recommended), or pass a function as the child.
Example:
Example Formatting Currency Values
Formatting Number using unit
Currently this is part of ES2020 NumberFormat.
We've provided a polyfill here and react-intl
types allow users to pass
in a sanctioned unit. For example:
#
FormattedNumberPartsbrowser support
This requires Intl.NumberFormat.prototype.formatToParts which is not available in IE11. Please use our polyfill if you plan to support IE11.
This component provides more customization to FormattedNumber
by allowing children function to have access to underlying parts of the formatted number. The available parts are listed here.
Props:
Example:
#
FormattedPluralThis component uses the formatPlural
API and Intl.PluralRules
has props
that correspond to Intl.PluralRulesOptions
.
Props:
By default <FormattedPlural>
will select a plural category (zero
, one
, two
, few
, many
, or other
) and render the corresponding React element into a React.Fragment
. If you need to customize rendering, you can either wrap it with another React element (recommended), or pass a function as the child.
Example:
#
FormattedListbrowser support
This requires Intl.ListFormat which has limited browser support. Please use our polyfill if you plan to support them.
This component uses formatList
API and Intl.ListFormat. Its props corresponds to Intl.ListFormatOptions
.
Props:
Example:
When the locale is en
:
#
FormattedDisplayNamebrowser support
This requires Intl.DisplayNames which has limited browser support. Please use our polyfill if you plan to support them.
This component uses formatDisplayName
and Intl.DisplayNames
has props
that correspond to DisplayNameOptions
. You might need a polyfill.
Props:
Example:
When the locale is en
:
#
FormattedMessageThis component uses the formatMessage
API and has props
that correspond to a Message Descriptor.
Props:
#
Message SyntaxString/Message formatting is a paramount feature of React Intl and it builds on ICU Message Formatting by using the ICU Message Syntax. This message syntax allows for simple to complex messages to be defined, translated, and then formatted at runtime.
Simple Message:
Complex Message:
See: The Message Syntax Guide.
#
Message DescriptorReact Intl has a Message Descriptor concept which is used to define your app's default messages/strings. <FormattedMessage>
have props which correspond to a Message Descriptor. The Message Descriptors work very well for providing the data necessary for having the strings/messages translated, and they contain the following properties:
id
: A unique, stable identifier for the messagedescription
: Context for the translator about how it's used in the UIdefaultMessage
: The default message (probably in English)
compile message descriptors
The babel-plugin-formatjs and @formatjs/ts-transformer packages can be used to compile Message Descriptors defined in JavaScript source files into AST for performance.
#
Message Formatting FallbacksThe message formatting APIs go the extra mile to provide fallbacks for the common situations where formatting fails; at the very least a non-empty string should always be returned. Here's the message formatting fallback algorithm:
- Lookup and format the translated message at
id
, passed to<IntlProvider>
. - Fallback to formatting the
defaultMessage
. - Fallback to translated message at
id
's source. - Fallback to
defaultMessage
source. - Fallback to the literal message
id
.
#
UsageBy default <FormattedMessage>
will render the formatted string into a <React.Fragment>
. If you need to customize rendering, you can either wrap it with another React element (recommended), specify a different tagName
(e.g., 'div'
), or pass a function as the child.
Example:
Example: function as the child
title
simple message
Messages can be simple strings without placeholders, and that's the most common type of message. This case is highly-optimized, but still has the benefits of the fallback procedure.
#
Rich Text Formatting<FormattedMessage>
also supports rich-text formatting by specifying a XML tag in the message & resolving that tag in the values
prop. Here's an example:
By allowing embedding XML tag we want to make sure contextual information is not lost when you need to style part of the string. In a more complicated example like:
#
Function as the childSince rich text formatting allows embedding ReactElement
, in function as the child scenario, the function will receive the formatted message chunks as a single parameter.
All the rich text gets translated together which yields higher quality output. This brings feature-parity with other translation libs as well, such as fluent by Mozilla (using overlays
concept).
Extending this also allows users to potentially utilizing other rich text format, like Markdown.