Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

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

<Form ... error={this.props.errorMessage ? true : false}>
like image 424
KevinS Avatar asked Dec 09 '17 23:12

KevinS


People also ask

Can I use ternary operator in JSX?

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.

How do you write expressions in JSX?

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.

How do you write ternary condition in react JS?

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.

Is it good to use ternary operator?

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.


1 Answers

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.

like image 87
Christian Santos Avatar answered Oct 03 '22 09:10

Christian Santos