Is there a better way to write this ternary expression in this snippet of JSX?
<Form ... error={this.props.errorMessage ? true : false}>
Use Ternary Operators in JSXYou can use curly braces inside JSX and write valid JavaScript expressions between them, including a ternary operator. You can use the ternary operator to configure dynamic classes in React. It is a short and simple syntax.
You can put any valid JavaScript expression inside the curly braces in JSX. For example, 2 + 2 , user.firstName , or formatName(user) are all valid JavaScript expressions.
The ternary operator, also called the conditional operator, is an alternative to the if...else statement. This operator has three parameters: A condition followed by ? (question mark) The expression to execute if the condition is true.
It's a good practice to use the ternary operator when it makes the code easier to read. If the logic contains many if...else statements, you should avoid using the ternary operators.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With