import { IntlProvider, addLocaleData, injectIntl } from 'react-intl';
import App from './app';
const locale = 'en'; // or 'fr' or whatever
<IntlProvider locale={locale} messages={messages[locale]}>
<App />
</IntlProvider>
Pluralization Rules (verbose docs): http://www.unicode.org/cldr/charts/28/supplemental/language_plural_rules.html More simplistic docs: https://formatjs.io/guides/message-syntax/
In the messages
below, productCount
is a variable that's passed in, and based on the number value, plural
will then
use pluralization rules like one
or other
to output a message like 1 color
or 2 colors
. It's a little confusing
because {productCount}
is a token that's replaced, and {color}
or {colors}
are static text values that will be used if
the pluralization rule is matched.
const messages = {
en: {
'card.colorsLabel': `{productCount} {productCount, plural,
one {color}
other {colors}
}`,
'card.customizeLabel': 'Customize',
currency: 'USD',
},
fr: {
'card.colorsLabel': `{productCount} {productCount, plural,
one {couleur}
other {couleurs}
}`,
'card.customizeLabel': 'Personnaliser',
currency: 'EUR',
},
};
The below formatting examples utilize the message data that was set up above. You'll notice that each call to formatMessage
requires an id
be passed. That id
is the key in the messages
.
intl.formatMessage({
id: 'card.customizeLabel',
})
Below, any occurance of productCount
in card.colorsLabel
will be replaced with colors.length
. So you could get
1 color
or 2 colors
depending on the Array length.
const colors = ['blue', 'gray'];
intl.formatMessage(
{ id: 'card.colorsLabel' },
{ productCount: colors.length }
)
Below price
will pull the currency
value from the current locale of messages
(so USD
for en
) and format the
message to $106.92
. If the locale
is switched to fr
, the message will be 106,92 €
.
const price = 106.92;
intl.formatNumber(price, {
style: 'currency',
currency: intl.formatMessage({ id: 'currency' }),
})