React Intl, how to add a number in a message?

4.2k Views Asked by At

I have a en.json file as below:

{
    "doorClosing": {
      "defaultMessage": "Doors closing",
      "description": "Elevator doors are being closed"
    },
    "floorSelected": {
      "defaultMessage": "Floor selected: {floorSelected}",
      "description": "`The floor ${lift.floorSelected} has been selected`"
    },
    "floorSelectedInvalid": {
      "defaultMessage": "Invalid floor",
      "description": "The selected floor is not valid"
    },
    "idle": {
      "defaultMessage": "",
      "description": ""
    },
    "init": {
      "defaultMessage": "Initialisation",
      "description": "The system is being initialized"
    },
    "liftMoving": {
      "defaultMessage": "Elevator moving",
      "description": "Elevator is being moved to the floor selected"
    }
}

Then later in the code, I use let dashboardMsg = intl.formatMessage({id:msg}); where msg is one of the key contained in the json file.
About the key floorSelected, when I use it ${lift.floorSelected} is not translated by the number contained in this variable.
What's wrong? Is there another way or do I have to do that manually?

3

There are 3 best solutions below

4
On BEST ANSWER

What you want is called formatted argument. It's part of the ICU Message Syntax which you can see here for more reference.

"floorSelected": {
  "id": "floorSelected",
  "defaultMessage": "Floor selected: {floorSelected}",
  "description": "The floor {floorSelected} has been selected"
},
...

In your code

const message = intl.formatMessage(messages.floorSelected, {
  floorSelected: lift.floorSelected
});

You can also specify the number type for the argument to customize how the number should be formatted. Here is an example:

Number: {num} {num, number, ::currency/USD} {num, number, ::compact-long}

When you call this method

intl.formatMessage(messages.numberExample, {
  num: 4200
})

It will be translated to this

Number: 4200 $4,200.00 4.2 thousand

Live Demo

Edit 64122522/react-intl-how-to-add-a-number-in-a-message

0
On

You can pass variables via values prop:

"floorSelected": {
  "id": "selected.floor",
  "defaultMessage": "Floor selected: {floorSelected}",
}

//...

let dashboardMsg = intl.formatMessage({id:msg, values: {floorSelected: 5})

Not sure if this is gonna work for description though.

0
On

formatMessage takes a message descriptor and optional values object as arguments.

formatMessage(messageDescriptor, values);

For your case

formatMessage({ id: msg }, { floorSelected: 3 })

If you ensure you add an id property to all your message descriptors then you won't need to construct an object with it on the fly each time you want to render the text.