Capítulo 16 de 116

Chapter 16: Conditional Rendering

Core Idea

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.

Key Concepts

  • 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.
  • Ternary 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.
  • The && 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 valuecount && <p>msgs</p> with count = 0 renders the literal 0, not nothing. Fix: force a boolean, count > 0 && <p>msgs</p>.
  • Variable assignment style: 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.

Code Examples

function Item({ name, isPacked }) {
  return (
    <li className="item">
      {name} {isPacked && '✅'}
    </li>
  );
}
  • What it demonstrates: the && 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).

Key Takeaways

  1. All conditional rendering is plain JavaScript control flow — there's no React-specific conditional syntax to learn beyond where {} is allowed.
  2. Never put a raw number on the left of && in JSX — it can render as a literal 0 instead of nothing. Coerce to boolean first (count > 0 && ...).
  3. Ternary branches aren't separate stateful "instances" — React only cares about an element's type and position when deciding whether to preserve or reset state (Ch 30).

Connects To

  • Ch 17 (Rendering Lists): the next JS-native technique (.map()) applied to JSX.
  • Ch 30 (Preserving and Resetting State): exactly how React decides whether swapped conditional branches keep or reset state.