5

ReactJS Tips & Tricks: Avoid Short-Circuit Conditional UI Rendering

 2 years ago
source link: https://dev.to/helderburato/reactjs-tips-tricks-avoid-short-circuit-conditional-ui-rendering-j5a
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

The goal of this articles is to share with you some insights that I have learned
over the last few years that I have been working with ReactJS.

I will start with a common one that is called Short-Circuit Conditional unexpected UI rendering.

What is a Short-Circuit conditional?

This conditional is a concise way to render UI components.

Example of the Short-Circuit conditional approach:

const Component = ({ number = 0 }) => number && <div>Current: {number}</div>
Enter fullscreen modeExit fullscreen mode

The component I mentioned before will backfire a 0.

Why does it render zero instead of the empty UI?

The comparison operators in JavaScript don't return boolean values, they return one of the compared values.

In the case mentioned above, when we check the number value it will render zero.

How to avoid the unexpected UI rendering

The way to avoid this issue is using the ternary comparison to be explicit about what will return in both scenarios.

Fixing the Component using the ternary comparison such as:

const Component = ({ number = 0 }) => (number ? <div>Current: {number}</div> : null)
Enter fullscreen modeExit fullscreen mode

Considering the value of number variable is zero, it will return null that is the second option from the ternary on this case React won't render because it is a null value.

Wrapping Up

If you think this series of articles is helpful to you, or do you want to discuss some programming topics, feel free to reach out to me at @helderburato.

Thanks! ⚡️


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK