Photo by Volodymyr Hryshchenko on Unsplash

Spot the Bug: To Do, Conditionally

Jack Taylor
2 min readJun 22, 2022

In this instalment of Spot the Bug, we have a ToDoList component which takes an array of items and renders them in a list. However, there’s a small bug in the code:

Solution

If you run the code, you’ll notice that tomorrow’s to do list doesn’t render nothing as expected, but rather renders 0.

This is because of the way JavaScript handles the && operator. In React, it’s common to use && to do conditional rendering, as if the left hand part of the && operator is falsy, the right hand side won’t be evaluated:

true && "hello world" // "hello world" will be rendered
false && "hello world" // nothing will be rendered

This works because React won’t render anything for the boolean value false. However, the issue with the ToDoList component is that we’re checking items.length, which returns 0 if there are no items — which React will render as a valid piece of JSX.

How do you fix it?

The simplest solution is to always use ternaries when doing conditional rendering in React:

This way you are telling React explicitly what to render if the left hand side of the ternary operation is falsy — in this case, if there are no items then we want to render null. As expected, nothing renders now for tomorrow’s to do list.

This is also a nice pattern to use in general as it forces you to think more explicitly about zero cases in your code. For example, in this case it might be nice to render some text telling the user that there are no items in their to do list.

And something to watch out for in the future that might help with conditional rendering is do expressions, which would allow us to do something like this:

return (
<nav>
<Home />
{
do {
if (loggedIn) {
<LogoutButton />
} else {
<LoginButton />
}
}
}
</nav>
)

This is currently in the proposal stage, but in my opinion is clearer and easier to follow than ternaries, especially when there are multiple nested conditions.

Thanks for reading, and if you found this useful then you might enjoy the previous instalment of Spot the Bug here.

Jack Taylor

I am a UI developer writing about JavaScript, React and tech in general. Currently working at Pleo.