1. 程式人生 > >5 Common Anti-Patterns in React

5 Common Anti-Patterns in React

&& — Your Frenemy…

Tom & Jerry are the most iconic frenemy duo: change my mind

Conditional rendering is something that I use often in React, as I’m sure many others do. I recently ran into an issue using the && operator that I couldn’t figure out for the life of me!

Picture this: you have a countdown timer in your application that counts down from 30 seconds. Our code might look something like this:

We’re using the && conditional operator to determine if we have a current count and are displaying it within the paragraph tags. But what will our output look like when we get to 0?

Our expected output would be 0 seconds left!. Our actual output would just be 0. This confused me at first until I did some digging…

It turns out that 0 is the only falsy that JSX renders as text. This means that 0 && 0 evaluates to 0 or false and JSX will just display the false 0 .

So, how do we fix this? The easiest approach would be to add the !! , or double not, operator to the left side of our conditional. This forces our currentCount

variable to be interpreted as a boolean. We’d end up with the following: