Skip to content

Instantly share code, notes, and snippets.

@the0neWhoKnocks
Last active August 23, 2018 17:32
Show Gist options
  • Save the0neWhoKnocks/4e94f034ce236a2f11400c892edbca12 to your computer and use it in GitHub Desktop.
Save the0neWhoKnocks/4e94f034ce236a2f11400c892edbca12 to your computer and use it in GitHub Desktop.
Using React-Intl

Using React-Intl


Setup

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>

Setting up messages

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',
  },
};

Formatting messages

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.

Formatting a Simple Message

intl.formatMessage({
  id: 'card.customizeLabel',
})

Formatting a Message with Tokens

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 }
)

Formatting a Price

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' }),
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment