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?
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;