Fix Seeing “0” in Your JSX Code

Publikováno: 9.7.2021

The early days of the web felt like the wild west when it came to coding practices — just make it work. Then we became enlightened to better practices, separating HTML from CSS and JavaScript. Then came React and JSX, where we combine JavaScript, HTML, and even CSS with Styled Components — what an elegant […]

The post Fix Seeing “0” in Your JSX Code appeared first on David Walsh Blog.

Celý článek

The early days of the web felt like the wild west when it came to coding practices — just make it work. Then we became enlightened to better practices, separating HTML from CSS and JavaScript. Then came React and JSX, where we combine JavaScript, HTML, and even CSS with Styled Components — what an elegant mess we’ve made!

Every once in a while part of that mess is me seeing 0 displaying in the output of my JSX code, and I’m reminded why: improper handling of variable typing, combined with using &&. Let me explain!

One of the popular patterns in JSX is:

<div>Some header</div>
{someValue && <div>Some header</div>}

The pattern makes sense but check out the difference in outputs between string and number types:

"0" && "Thing"
> "Thing"
0 && "Thing"
> 0

Note that a string value of 0 allows the second value to be returned, but a number typed 0 simply returns the 0. The best practice is always to cast the value to a Boolean in your JSX:

{Boolean(value) && ....}

Typescript and even PropTypes can help to catch these issues but even seasoned veterans sometimes hit these pain points.

The post Fix Seeing “0” in Your JSX Code appeared first on David Walsh Blog.

Nahoru
Tento web používá k poskytování služeb a analýze návštěvnosti soubory cookie. Používáním tohoto webu s tímto souhlasíte. Další informace