If
condition
is false, the second operand of the&&
operator is not evaluated. If it is true, the second operand — or the JSX we wish to render — is returned.
It’s important to note that this can have different behavior, due to the nature of the JavaScript &&
operator. To quote MDN:
…the
&&
and||
operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they will return a non-Boolean value.
So, take care to not write shorthand like array.length && <ul ...>
because this will print the first falsy value, 0
. (The only other renderable falsy value is NaN
.) Of course, this is easily fixed by writing clearer code: array.length > 0
.
The one other important case is if the entire component renders conditionally, because React will throw an error if a render function returns undefined
. The other falsy values null
and false
will work, and ''
will effectively render nothing, though React will attach an unnecessary empty text node in the DOM (tested this with ReactDOM.findDOMNode()
on a component that returned ''
).