One can use logical AND (&&
) operator to conditionally render in React (aka short-circuit evaluation). myCondition
&& <MyElement />
will return <MyElement />
if myCondition
is true
and
false
otherwise. As React renders boolean values to nothing, when condition is false
, nothing will be rendered as intended.
But if the condition has a non-boolean value which evaluates to false
(e.g. 0
), that value will leak into the rendered
result.
This rule will report when the condition has type number
or bigint
.
If React Native is used, the type string
will also raise an error, as your render method will crash if you render 0
,
''
, or NaN
.
Note that along with short-circuit evaluation, in order to achieve conditional rendering it’s possible to use ternary operator (myCondition ?
<MyElement /> : null
), which is less error-prone in this case as both return values are explicit.
Noncompliant Code Example
function Profile(props) {
return <div>
<h1>{ props.username }</h1>
{ props.orders && <Orders /> } { /* Noncompliant, 0 will be rendered if no orders available */ }
</div>
}
Compliant Solution
function Profile(props) {
return <div>
<h1>{ props.username }</h1>
{ props.orders > 0 && <Orders /> }
</div>;
}
or
function Profile(props) {
return <div>
<h1>{ props.username }</h1>
{ props.orders ? <Orders /> : null }
</div>;
}
See