Things you didn’t know about JS Data Types handling in React
React uses jsx
for the HTML templating. This is very powerful and easy to get started with. It is great while displaying data to using the power of JS in templating.
But still, I see many developers making mistakes and confused about how React will interpolate and render the native data types on the HTML.
Below is the snippet for the thoughts to get started with
{props.heroList.length && <HeroListContainer list={list} />}
What will be rendered if heroList=[]
. If you know what is the problem in the above snippet then you can skip this article. If not then follow.
The problem with the above snippet is it will print 0
which is an undesired behavior.
You can also play with the embedded codesandbox
So it’s clear that the following will not be rendered by React while generating HTML.
- Booleans (true/false)
- null
- undefined
- String (empty)
- Array (empty)
- Arrow Function
- Function
- Set (empty)
We can clearly see that every iterable in javascript will be rendered via React. Object
will result in an error. We have used ErrorBoundry
to handle this error.
I was surprised to see that functions
don’t throw an error, they are simply not rendered. This can be a trick question to ask and remember. Let me know which one surprised you!