4

I want to localize my component. I use yahoo/react-intl lib. I define some messages

const messages = defineMessages({
    greeting: {
        id: 'app.home.greeting',
        description: 'Message to greet the user.',
        defaultMessage: 'Hello!'
    },
  });

I don't know how to define a localizable text for message so I got this error

app.js:27785[React Intl] Missing message: "app.home.greeting" for locale: "nl", using default message as fallback.

Example of using

<input type="text" {...firstName} placeholder={intl.formatMessage(messages.greeting)} />

Does anyone know how to define localized messages? It looks not possible to do this with defineMessages. Thanks in advance.

BILL
  • 4,711
  • 10
  • 57
  • 96

1 Answers1

7

defineMessages is designed to work with the babel-plugin of react-intl.

In fact, it just helps you when extracting message defined somewhere in your code. This is useful in large code bases to keep the message-ids and translations in sync.

However, whether you use defineMessages or not you still need to provide the translations like this:

const translations = {
    'en-US': {
        'app.home.greeting': 'Hello!',
        'app.home.color.description': 'Please choose a color',
    },
    'en-GB': {
        'app.home.greeting': 'Hello!',
        'app.home.color.description': 'Please choose a colour',
    },
    de: {
        'app.home.greeting': 'Hallo!',
        'app.home.color.description': 'Bitte eine Farbe auswählen',
    }
 }

<IntlProvider locale="en" messages={translations.en}>
    <FormattedMessage
        id='app.home.color.description'
        description='A task description to choose a color'
        defaultMessage='Please choose a color'
    /> 
    <input type="text" {...firstName} placeholder={intl.formatMessage(messages.greeting)} />
</IntlProvider>

Of course you don’t need to wrap everything in a IntlProvider. Simply add one IntlProvider around your top-level/app component.

Nighto
  • 3,994
  • 3
  • 23
  • 28
wollnyst
  • 1,683
  • 1
  • 17
  • 20
  • Yep, but actually I should define two messages with different ids for uk en translates. Am I correct? – BILL May 14 '16 at 13:55
  • No, you use one id for every string. I have edited my answer to clarify this. – wollnyst May 15 '16 at 05:38
  • 2
    where is that `en` in `translations.en` coming from? and how would you pass that `translations` object globally so you can reuse it on various components? – Sagiv b.g Mar 14 '17 at 08:32
  • @Sag1v I guess it should be `translations['en-US']` – Vernon Apr 10 '17 at 14:21