Avoid bugs by not using `&&` in React components
If you’ve seen any React application, you know how to conditionally render parts of a component depending on props and state. Although there are multiple ways of conditional rendering, this article focuses on the JavaScript &&
operator. The main reason for this emphasis is that the&&
operator often leads to UI bugs, which can be easily avoided and it’s often not mentioned.
Content
- How “&&” Works
- Why Not To Use “&&”
- What To Use Instead Of “&&”
How “&&” Works
A classic example of its use in React would be:
function MyComponent({ condition }) {
return (
<div>
<h1>Title</h1>
{condition && <ConditionalComponent />}
</div>
);
}
Briefly summarized:
- if
condition
is a truthy value,<ConditionalComponent />
is rendered - if
condition
is a falsy value,<ConditionalComponent />
is not rendered
Why is that? It’s nothing React specific but rather a behavior of JavaScript and other programming languages called short-circuit evaluation. I.e., if the first operand (condition
) is falsy, the AND operator (&&
) stops and it does not evaluate the second operand (<ConditionalComponent/>
).
You can try that in your browser by running the code snippet below in Console:
// This will display an alert box.
true && alert('Hello');
// This won't do anything.
false && alert('Not hello');
Why Not To Use “&&”
The short syntax of &&
is often preferred and it works. But! Just because you can doesn’t mean you should.
In our case from above, if condition
evaluates to true
or false
, you get what you’d expect — <ConditionalComponent />
is or is not rendered respectively. All good so far. However, if condition
doesn’t evaluate to a boolean, it may cause trouble.
For example:
- if
condition
is0
,0
is displayed in the UI - if
condition
isundefined
, you’ll get an error:"Uncaught Error: Error(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null."
What To Use Instead Of “&&”
To avoid showing something you don’t want in the UI, such as 0
, that could mess up the layout, use the JavaScript ternary operator instead. I.e.,
condition ? <ConditionalComponent /> : null;
Conclusion
To prevent avoidable UI bugs, use the JavaScript ternary operator for conditional rendering of React components instead of the logical AND operator. It’s a simple spell but quite unbreakable 🧙♂️
🔴 BAD condition && <ConditionalComponent /> 🟢 GOOD condition ? <ConditionalComponent /> : null