Capítulo 20 de 116

Chapter 20: Responding to Events

Core Idea

Event handlers are functions defined inside a component and passed (never called) to a JSX tag as a prop; on custom components those prop names are entirely up to you, but browser events still bubble underneath, and stopPropagation()/preventDefault() are two unrelated tools for controlling that.

Key Concepts

  • Adding a handler: define a function inside the component, then wire it with onClick={handleClick} — no parentheses, or it fires during render instead of on click.
  • Custom component event props are free-form: a built-in tag like <button> only understands real browser event names (onClick), but your own component's prop can be named anything — convention is on + capitalized verb (onSmash, onPlayMovie), especially useful when a component supports several distinct interactions.
  • Event propagation (bubbling): a click on a nested <button> also fires onClick handlers on ancestor elements that have one, in order from the element outward.
  • e.stopPropagation(): called on the event object inside a handler, stops the event from reaching ancestor handlers — use when a child's click shouldn't also trigger the parent's handler (e.g. a button inside a clickable toolbar).
  • e.preventDefault(): stops the browser's default behavior for events that have one — e.g. a <form onSubmit> reloading the page by default. Unrelated to propagation: one stops handlers from firing, the other stops built-in browser behavior.
  • Event handlers are the sanctioned place for side effects — unlike the render body (Ch 18), which must stay pure, a click handler is expected to change state, make a request, or otherwise cause an effect, because it runs in response to a specific interaction, not during rendering.

Code Examples

function Button({ onClick, children }) {
  return (
    <button onClick={e => { e.stopPropagation(); onClick(); }}>
      {children}
    </button>
  );
}
  • What it demonstrates: stopPropagation() used so a button's own click doesn't also trigger a parent container's click handler.

Key Takeaways

  1. Pass the function reference (onClick={handleClick}), never call it inline (onClick={handleClick()}) — the same rule from Ch 1, now with the "why": calling it fires immediately during render.
  2. stopPropagation() and preventDefault() solve different problems — don't reach for one when you mean the other.
  3. Side effects (state changes, requests, alerts) belong in event handlers, not in the render body — this is the practical counterpart to the purity rule from Ch 18.

Connects To

  • Ch 18 (Keeping Components Pure): why side effects are excluded from render but welcome in handlers.
  • Ch 21 (State: A Component's Memory): the most common thing an event handler does — call a state setter.
  • Ch 15 (Passing Props to a Component): the mechanism behind custom event-prop names like onSmash.