Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 14, 2022 06:56 pm GMT

Don't use '&&' for conditional reasoning

We often use '&&' to display a component if a given condition is true and to not display it when the condition is false.

function BigComponent({condition}) {    return (        <div>          <p> After this we will try to render a component based              on a condition           </p>          {condition && <NextComponent/>}        </div>    )}export default BigComponent

So basically, here the condition is evaluated and only if the left side of '&&' is true, we move forward and then render the second half, that is the component.

This is called short circuiting.

There are two problems here:

  1. The output to the condition must be boolean. If the condition gives 0, it will render 0.

  2. If the result from the condition is undefined, it will give an error.

What to do then?

To avoid something like displaying a zero or getting an error, we can use a ternary operator:

condition ? <ConditionalComponent /> : null

which translates to: "if condition is true do the first statement else execute the statement after the semicolon (:)"

Happy Coding!


Original Link: https://dev.to/aishanipach/dont-use-for-conditional-reasoning-3525

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To