Better ways to use “&&” for Conditional Rendering in React

Avoid bugs by not using `&&` correctly for conditional rendering in React components

In 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

  1. How “&&” Works
  2. Why Not To Use “&&” with direct conditions
  3. What To Use Instead Of “&&” with direct conditions

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 “&&” with direct condition

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 is 0, 0 is displayed in the UI
  • if condition is undefined, 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 “&&” with direct condition

To avoid showing something you don’t want in the UI, such as 0, that could mess up the layout, use the JavaScript typecasting to Boolean or use ternary operator instead. i.e.-

!!condition && <ConditionalComponent />

OR

Boolean(condition) && <ConditionalComponent />

OR

condition ? <ConditionalComponent /> : null;

Conclusion

To prevent avoidable UI bugs, use the JavaScript typecasting to Boolean or use ternary operator for conditional rendering of React components instead direct logical AND operator. It’s a simple spell but quite unbreakable 🧙‍♂️

🔴 BAD
condition && <ConditionalComponent />
🟢 GOOD
!!condition && <ConditionalComponent />
OR
Boolean(condition) && <ConditionalComponent />
OR
condition ? <ConditionalComponent /> : null

You might also like