4

Is it possible to have an if/else in a FormatJS message?

Example

I have a boolean variable isDay that should determine what message is shown. When true I want to show the wording "Day" and when false I want to show Night.

// message string
message = "Day";

// React component
<FormattedMessage
 id="message"
 values={{isDay: true}}
/>

I want to be able to do something like:

message = "{if isDay}Day{else}Night{endif}";

I know the above is not the actual syntax, but wondering if something like this is possible with FormatJS?

Carlton
  • 531
  • 1
  • 5
  • 19

1 Answers1

7

Found a solution using the ICU Message select syntax.

message = "{isDay, select, true {Day} other {Night}}";
Carlton
  • 531
  • 1
  • 5
  • 19
  • 2
    It seems that `other` is required. https://formatjs.io/docs/core-concepts/icu-syntax/#select-format – User 28 Mar 30 '22 at 01:19