Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When to use ternary operator over the logical operator in React to render conditionally only when there are items

I have to (conditionally) render some React JSX markup, only when it contains items (from api).

 return items?.length ? (
  <div>
    <MyBlock data={myBlockData} />
  </div>
  ) : null;

But what’s the difference between a Ternary null operator (like above) or a Logical operator like:

 return items?.length && (
  <div>
    <MyBlock data={myBlockData} />
  </div>
  );

What to use in my case?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Difference is between what JSX will get constructed when you have false(y) condition.

The ternary operator will return null and therefore nothing shows up on the DOM node, whereas in case of logical operator, the false(y) value will evaluate to 0, and therefore, you’ll see "0" getting added as a text node in your DOM.

If you wish to use the logical operator to conditionally render, it’s always better to add a fallback.

return items?.length&& (
   <div>
     <MyBlock data={myBlockData} />
   </div>
  ) ||
  null;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading