Categories
jsx logical-operators reactjs

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

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