Capítulo 15 de 116

Chapter 15: Passing Props to a Component

Core Idea

Props are a component's only argument — a read-only object passed down from a parent that lets parent and child evolve independently, the same role function arguments play for ordinary functions.

Key Concepts

  • Passing: add attributes in JSX exactly like HTML (<Avatar person={{...}} size={100} />); any JS value works, including objects/arrays/functions.
  • Reading: destructure in the parameter list — function Avatar({ person, size }) {} — equivalent to receiving one props object and reading props.person/props.size.
  • Default values: function Avatar({ size = 100 }) — applies when the prop is missing or explicitly undefined. Passing null or 0 does not trigger the default.
  • Spread forwarding: <Avatar {...props} /> forwards every prop without listing names — convenient when a wrapper doesn't touch any prop directly, but overusing it usually signals you should split the component or use children instead.
  • children prop: JSX nested between a component's opening/closing tags (<Card><Avatar /></Card>) arrives as props.children on Card. This is the mechanism behind every generic wrapper (panels, layouts, grids) that doesn't need to know what it's wrapping.
  • Props are immutable snapshots, not live bindings. A prop's value can change between renders (a parent passing a new value causes a new render with new props), but a component can never reach up and mutate its own props — "changing" a prop means asking the parent to pass a different value, which usually means the parent needs state (Ch 21).

Code Examples

function Card({ children }) {
  return <div className="card">{children}</div>;
}

// usage:
<Card>
  <Avatar person={{ name: 'Katsuko Saruhashi', imageId: 'YfeOqp2' }} size={100} />
</Card>
  • What it demonstrates: Card never needs to know what it's wrapping — the nested <Avatar /> JSX arrives as Card's children prop.

Key Takeaways

  1. Destructuring in the function signature ({ person, size }) is the idiomatic way to read props — don't reach for the whole props object unless you genuinely need it.
  2. A default value (size = 100) only kicks in for missing/undefined, not for falsy-but-present values like 0 or null — a common source of "why isn't my default applying" bugs.
  3. children is the pattern for building generic layout/wrapper components — reach for it instead of heavy spread-forwarding when a component's job is just "wrap arbitrary content."
  4. Props never mutate in place; "changing" one always means the parent re-rendering with a new value, which is what state (Ch 21) exists to drive.

Connects To

  • Ch 19 (Your UI as a Tree): how children decouples a component's render-tree position from its module-import location.
  • Ch 21 (State: A Component's Memory): what actually drives a prop to a new value over time.
  • Ch 14 (JavaScript in JSX with Curly Braces): the {} syntax used to pass non-string prop values.