Photo by Volodymyr Hryshchenko on Unsplash

Spot the Bug: To Do, Conditionally

Jack Taylor

--

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?

--

--

Jack Taylor
Jack Taylor

Written by Jack Taylor

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

No responses yet