Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Utilizing AND statement (two conditions) inside react ternary operator

below is a inline if with logical && operator that renders a component if this.state.isHidden is false.

<div>{!this.state.isHidden && <ShowThisComponent /> }</div>

The above line works as expected. My problem is that I cannot figure out how to add a second condition to be met (e.g var1 === var2) to the above line. So that if both return true, the component gets displayed. How can I do this? thanks

I've looked at the documentation (https://reactjs.org/docs/conditional-rendering.html#inline-if-with-logical-ampamp-operator) could not find an answer

like image 350
zamzam Avatar asked Apr 24 '18 08:04

zamzam


People also ask

Why is && used in React?

Inline If with Logical && Operator It works because in JavaScript, true && expression always evaluates to expression , and false && expression always evaluates to false . Therefore, if the condition is true , the element right after && will appear in the output. If it is false , React will ignore and skip it.

Should you use ternary or && operator to conditionally render React components?

The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement. When condition evaluates to true, the operator returns “This is True”; otherwise (when condition is falsy) it returns “This is False”.

How do you check multiple conditions in React?

If statements also work when you have multiple conditions that you want to check for. Notice that we can reuse the if-statement and do not have to write if-else or if-else-if, which cuts down on the code that we have to write and is still just as readable.


1 Answers

This is how the operator works:

{<any boolean statement> && <Component-to-be-displayed />}.

-or-

{(<any boolean statement>) && <Component-to-be-displayed />} ... it's always a good idea to use parentheses when analysing boolean statements

In your case it would look something like this :

(!this.state.isHidden && var1 === var2) && <Component-to-be-displayed />

so think of the operator like this:

if condition is true && render component

You can also perform an if-statement:

{(<any boolean statement>) ? <Component-to-be-displayed-if-true /> : <Component-to-be-displayed-if-false /> }

you can think of this operator like this:

if condition is true ? render component A : else render component B

like image 149
dakoto Avatar answered Oct 05 '22 11:10

dakoto