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.