Fix Seeing “0” in Your JSX Code

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.

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.


Print Share Comment Cite Upload Translate
APA
David Walsh | Sciencx (2024-03-29T15:20:22+00:00) » Fix Seeing “0” in Your JSX Code. Retrieved from https://www.scien.cx/2021/07/09/fix-seeing-0-in-your-jsx-code/.
MLA
" » Fix Seeing “0” in Your JSX Code." David Walsh | Sciencx - Friday July 9, 2021, https://www.scien.cx/2021/07/09/fix-seeing-0-in-your-jsx-code/
HARVARD
David Walsh | Sciencx Friday July 9, 2021 » Fix Seeing “0” in Your JSX Code., viewed 2024-03-29T15:20:22+00:00,<https://www.scien.cx/2021/07/09/fix-seeing-0-in-your-jsx-code/>
VANCOUVER
David Walsh | Sciencx - » Fix Seeing “0” in Your JSX Code. [Internet]. [Accessed 2024-03-29T15:20:22+00:00]. Available from: https://www.scien.cx/2021/07/09/fix-seeing-0-in-your-jsx-code/
CHICAGO
" » Fix Seeing “0” in Your JSX Code." David Walsh | Sciencx - Accessed 2024-03-29T15:20:22+00:00. https://www.scien.cx/2021/07/09/fix-seeing-0-in-your-jsx-code/
IEEE
" » Fix Seeing “0” in Your JSX Code." David Walsh | Sciencx [Online]. Available: https://www.scien.cx/2021/07/09/fix-seeing-0-in-your-jsx-code/. [Accessed: 2024-03-29T15:20:22+00:00]
rf:citation
» Fix Seeing “0” in Your JSX Code | David Walsh | Sciencx | https://www.scien.cx/2021/07/09/fix-seeing-0-in-your-jsx-code/ | 2024-03-29T15:20:22+00:00
https://github.com/addpipe/simple-recorderjs-demo