Logical AND (&&
) operator is sometimes used to conditionally render in React (aka short-circuit evaluation). For example,
myCondition && <MyElement />
will return <MyElement />
if myCondition
is true
and false
otherwise.
React considers false
as a 'hole' in the JSX tree, just like null
or undefined
, and doesn’t render anything
in its place. But if the condition has a falsy
non-boolean value (e.g. 0
), that value will leak into the rendered
result.
This rule will report when the condition has type number
or bigint
.
In the case of React Native, the type string
will also raise an error, as your render method will crash if you render 0
,
''
, or NaN
.
function Profile(props) {
return <div>
<h1>{ props.username }</h1>
{ props.orders && <Orders /> } { /* Noncompliant: 0 will be rendered if no orders available */ }
</div>;
}
Instead, make the left-hand side a boolean to avoid accidental renderings.
function Profile(props) {
return <div>
<h1>{ props.username }</h1>
{ props.orders > 0 && <Orders /> }
</div>;
}
Another alternative to achieve conditional rendering is using the ternary operator (myCondition ? <MyElement /> : null
), which
is less error-prone in this case as both return values are explicit.
function Profile(props) {
return <div>
<h1>{ props.username }</h1>
{ props.orders ? <Orders /> : null }
</div>;
}