FormattedMessage

February 21, 2020 ยท View on GitHub

Formats a message based on the locale, variables and options.

Messages must be loaded before they can be used by FormattedMessage. This is done using the loadMessages utility available as an import from React Native Globalize or from the object returned by useGlobalize.

Messages are formatted using the ICU message format pattern and support powerful logic, such as pluralization and gender inflections. Check out the advanced examples at the bottom of this page, and if you want more information, take a look at the ICU message format spec.

Usage

import { loadMessages, FormattedMessage } from 'react-native-globalize';

loadMessages({
  de: {
    welcome: 'Hallo, heute ist der {date}',
  },
  en: {
    welcome: 'Hello, today is {date}',
  },
  es: {
    welcome: 'Hola, hoy es {date}',
  },
})

const ExampleComponent = () => (
  <FormattedMessage
    id="welcome"
    values={{
      date: <FormattedDate value={new Date(2020, 0, 1)} date="long" />,
      // Variable value can also be a string
      date: 'awesome',
    }}
  />
);
// Hello, today is January 1, 2020
// Hello, today is awesome

Props

Note: All other props are treated as variables and are merged into values. However, using values is recommended in case props change in the future. For now, <FormattedMessage id="welcome" date="awesome" /> is equivalent to <FormattedMessage id="welcome" values={{ date: 'awesome' }} />.

defaultMessage

TypeRequiredDefaultDescription
stringNononeA default string used if a message with the specified id has not been loaded (useful when dynamically loading messages).
<FormattedMessage
  id="unknown/key"
  defaultMessage="Oops"
/>
// Oops

Note: By default, a error is emitted and logged to the console in development mode, so you may still see a React Native error/red screen when developing. However, if you dismiss the error screen, you'll see the defaultMessage value used as expected. You can override the default error logging behavior with the onError prop on GlobalizeProvider.

id

TypeRequiredDefaultDescription
stringYesnoneMessage identifier.

values

TypeRequiredDefaultDescription
objectNo{}Variables for replacement in message.

Advanced Examples

See more advanced message examples with gender and plural inflections in the formatMessage docs.