Way to Implement Conditionals in React JS

Conditional expressions in react js are used to render the components or the elements of components according to the conditions. For example, if your cart is empty then show “Your cart is empty” else show the cart items.

1. Logical AND Operator :

Logical AND operator is used to render the components according to a condition. The first statement is condition then && (AND Operator) and then the components or element. Note that inside javascript, we use && for writing conditions inside the if-else statement, there it evaluates both the expression and it the condition satisfies then it executes the block, but in React JS, inside return statement where we write JSX, it evaluates the first condition and renders the second statement, which is a component or element.

2. Ternary Operator :

We can say that it is a short form of the if-else statement, which can be written in one line.

Syntax : condition ? expression1 : expression2

If the condition is true then execute expression1, else expression2

3. if Statement :

It is a simple if statement, which can be paired with else or a bunch of else-if statements.

Output will be same using all the 3 ways.

Leave a Reply

Your email address will not be published. Required fields are marked *