Capítulo 16 de 116
React has no special conditional syntax — branching what renders is done with ordinary JavaScript (if, ? :, &&, or a variable reassignment), and the "shortcut" operators each carry one specific gotcha worth memorizing.
if/return: a component can return an entirely different JSX tree per branch — including null to render nothing. Returning null directly from a component is uncommon in practice (it can surprise a caller); more often the parent decides whether to include the child at all.cond ? <A /> : <B />: works inline inside JSX, unlike if. The two branches are not different "instances" in any stateful sense — JSX elements are lightweight descriptions, not DOM nodes, so a ? <X/> : <X/> and just <X/> behave equivalently for state purposes (see Ch 30).&& shortcut cond && <A />: renders <A /> when cond is truthy, otherwise renders nothing — because React treats false/null/undefined as a "hole" in the tree.&& number pitfall: JS coerces the left side to boolean for the test, but if the left side itself is falsy-and-non-boolean (e.g. 0), the whole expression evaluates to that value — count && <p>msgs</p> with count = 0 renders the literal 0, not nothing. Fix: force a boolean, count > 0 && <p>msgs</p>.let content = name; if (isPacked) content = <del>{name} ✅</del>; return <li>{content}</li>; — most verbose, most flexible; reach for it when ternary/&& chains get hard to read.function Item({ name, isPacked }) {
return (
<li className="item">
{name} {isPacked && '✅'}
</li>
);
}
&& shortcut for "render this only when true" — and the exact shape of the pitfall (if isPacked were 0 instead of a boolean, it would render 0).{} is allowed.&& in JSX — it can render as a literal 0 instead of nothing. Coerce to boolean first (count > 0 && ...)..map()) applied to JSX.