Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define localization with defineMessages method?

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.

like image 426
BILL Avatar asked Mar 13 '23 07:03

BILL


1 Answers

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.

like image 118
wollnyst Avatar answered Mar 20 '23 06:03

wollnyst