Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use placeholder with intl.formatMessage

I'm trying to use react-intl to add localization to my app. Like this

<FormattedHTMLMessage id="marker.title" values={{
        name: (b.name !== null ? b.name : "Bench"),
        seats: Tools.showValue(b.seats),
        material: Tools.showValue(b.material),
        color: Tools.getColorNameFromInt(b.color),
        lat: b.lat,
        lng: b.lng,
    }}/>

But I need a string so I tried this

const title = this.props.intl.formatMessage({
    id: "marker.title",
    values: {
        name: (b.name !== null ? b.name : "Bench"),
        seats: Tools.showValue(b.seats),
        material: Tools.showValue(b.material),
        color: Tools.getColorNameFromInt(b.color),
        lat: b.lat,
        lng: b.lng,
    }
});

and I get the following error message:

Error: The intl string context variable 'name' was not provided to the string '{name}<br/>Seats: {seats}<br/>Material: {material}<br/>Color: {color}<br/>Location: {lat} / {lng}'

en.json

{
  "marker.title": "{name}<br/>Seats: {seats}<br/>Material: {material}<br/>Color: {color}<br/>Location: {lat} / {lng}"
}
like image 431
cromir Avatar asked May 03 '18 09:05

cromir


People also ask

What does Intl formatMessage return?

formatMessage returns an array instead of a string #1681.

What is IntlProvider in react?

IntlProvider​ React Intl uses the provider pattern to scope an i18n context to a tree of components. This allows configuration like the current locale and set of translated strings/messages to be provided at the root of a component tree and made available to the <Formatted*> components.


1 Answers

Figured it out if you do it like this it will work

this.props.intl.formatMessage({id: "marker.title"}, {
                name: (b.name !== null ? b.name : "Bench"),
                seats: Tools.showValue(b.seats, this.props.intl),
                material: Tools.showValue(b.material, this.props.intl),
                color: Tools.getColorNameFromInt(b.color, this.props.intl),
                lat: b.lat,
                lng: b.lng,
            });

Let's hope I find this answer again when I'm stuck at this thing again.

like image 135
cromir Avatar answered Sep 21 '22 23:09

cromir