Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 710
learner Avatar asked Oct 14 '25 14:10

learner


1 Answers

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

like image 124
NearHuscarl Avatar answered Oct 18 '25 14:10

NearHuscarl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!