Capítulo 13 de 116

Chapter 13: Writing Markup with JSX

Core Idea

JSX exists because rendering logic and markup are inherently coupled — React keeps them together in one component instead of splitting them across separate HTML/JS files, but JSX itself is stricter than HTML and has three concrete rules for converting existing HTML.

Key Concepts

  • JSX vs. React: separate things, usually used together but independently swappable — JSX is a syntax extension, React is a library.
  • Rule 1 — single root element: a component can only return one root element. Wrap siblings in a <div>, or use an empty Fragment <>...</> when you don't want an extra DOM node. Under the hood JSX becomes plain JS objects, and a function can't return two objects unwrapped — that's the real reason for this rule.
  • Rule 2 — close every tag: self-closing elements need the explicit slash (<img />, not <img>); wrapping tags need an explicit close (<li>item</li>).
  • Rule 3 — camelCase most attributes: JSX attributes become JS object keys, so dash-containing or reserved-word HTML attributes get renamed — stroke-widthstrokeWidth, classclassName (matching the DOM's own className property). Exception: aria-* and data-* keep their dashes for historical reasons.
  • Practical tip: an HTML→JSX online converter handles the tedious parts of migrating existing markup; still worth understanding the rules to write JSX directly.

Code Examples

<>
  <img src="..." alt="Hedy Lamarr" className="photo" />
  <ul>
    <li>Invent new traffic lights</li>
  </ul>
</>
  • What it demonstrates: all three rules at once — Fragment wrapper for multiple roots, self-closed <img />, and className instead of class.

Key Takeaways

  1. If a component returns multiple sibling elements, wrap them — a <div> when you want the extra node in the DOM, a Fragment (<>...</>) when you don't.
  2. React's on-screen error messages for malformed JSX are specific enough to follow directly — read them before guessing at a fix.
  3. Attribute casing is a mechanical rule (camelCase, className), not a style preference — get it wrong and React logs a console suggestion, but it won't silently work like HTML would.

Connects To

  • Ch 14 (JavaScript in JSX with Curly Braces): how to embed dynamic values inside this markup.
  • Ch 67 (Fragment): the API reference for the <>...</> shorthand.