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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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

Method 3

{ (!this.state.isHidden && var1 === var2) && <ShowThisComponent /> }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x