Reputation: 3903
Is it possible to render an element based on a IF/OR statement?
I tried something like:
{!this.props.this || this.props.that && <button>Some button</button>}
but that doesn't work.
Upvotes: 5
Views: 17551
Reputation: 141
I assume you want to know the equivalent of
if (!this.props.this || this.props.that) {
// Render the button
}
The reason your code doesn't work that way is because of the precedence of &&
and ||
. The &&
is evaluated first, but you really want the combined condition to evaluate first.
You could use a ternary as others have suggested, but all you technically need is parentheses
{(!this.props.this || this.props.that) && <button>Some button</button>}
That way, you don't need a redundant null
Upvotes: 4
Reputation: 1793
The official documentation on this is pretty good. I find it cleanest to use ternary operators, which work as follows:
{(!this.props.this || this.props.that) ? <button>Some button</button> : null }
You can of course have a different component render if false instead of just null
.
Upvotes: 0
Reputation: 628
Yes, it's possible. Use ternary operator:
{
(!this.props.this || this.props.that) ? <button /> : null
}
You can also use React.Fragment to render more complex elements structure without container, for example
{
this.props.test ? (
<React.Fragment>
<ChildA />
<ChildB />
<ChildC />
</React.Fragment>
) : null
}
Note, that when you return null React treats it as nothing to render.
Upvotes: 14