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
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.
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”.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With