8

Is there a better way to write this ternary expression in this snippet of JSX?

<Form ... error={this.props.errorMessage ? true : false}>
KevinS
  • 7,715
  • 4
  • 38
  • 56

2 Answers2

9

You can shorten it slightly by:

<Form ... error={!!this.props.errorMessage}>

!! will turn a value into true or false depending on whether that value is truthy or falsy.

Christian Santos
  • 5,386
  • 1
  • 18
  • 24
  • Thanks. I'm pretty new to JS. Can you tell me if this is widely used or is it something that would leave most people confused. – KevinS Dec 09 '17 at 23:43
  • 1
    In my experience, `!!` is usually not JS 101 and most JS devs come across it by chance, so it depends -- if you're on a team where most are seasoned JS developers, they will have seen this syntax before. If members of the team are new to JS and have experience with other programming languages (especially static ones), I would say leaving it the way you originally had it is clearer. – Christian Santos Dec 09 '17 at 23:52
3

You can just double negate errorMessage prop:

<Form ... error={!!this.props.errorMessage}>
Cleiton
  • 17,663
  • 13
  • 46
  • 59