Capítulo 99 de 116

Chapter 99: <select>

Core Idea

<select> follows the same controlled/uncontrolled split as <input> (Ch 98), but the selected value lives on the <select> element itself via value/defaultValue rather than on the individual <option> children — React diverges here from raw HTML, which marks the selected option with a selected attribute instead.

Key Concepts

  • Controlled: <select value={fruit} onChange={e => setFruit(e.target.value)}> — the parent <select> carries the current value; each <option value="..."> just defines what's selectable, none of them carry a selected attribute directly.
  • Uncontrolled: <select defaultValue={initialFruit}> — same idea as defaultValue on <input>, letting the DOM own the selection after initial render.
  • Multi-select (multiple attribute): value becomes an array of selected option values instead of a single string, and onChange needs to read e.target.selectedOptions (or similar) to reconstruct that array.
  • This differs from plain HTML, where you'd normally add selected to the chosen <option> — React's controlled model intentionally centralizes selection state on the <select> itself for consistency with how <input>/<textarea> work.

Code Examples

<select value={fruit} onChange={e => setFruit(e.target.value)}>
  <option value="apple">Apple</option>
  <option value="banana">Banana</option>
</select>
  • What it demonstrates: the selected value driven entirely by the <select>'s own value prop, not by a selected attribute on either <option>.

Key Takeaways

  1. Set value/defaultValue on <select> itself, never selected on an individual <option> — that's the one place React's API meaningfully diverges from plain HTML syntax.
  2. For multiple, value is an array and reading the new selection from onChange requires iterating selectedOptions, not just e.target.value.
  3. The controlled/uncontrolled choice and its trade-offs mirror <input> exactly — same mental model, different element.

Connects To

  • Ch 98 (<input>): the controlled/uncontrolled pattern this element follows.
  • Ch 17 (Rendering Lists): dynamically generating <option> elements from an array typically needs key.