liveBook · Manning

Dropdown

As explained in React Quickly, Second Edition

A select box is an HTML control that lets a user choose one or more options from a list.

A dropdown, or select box, lets a user choose one or more options. In a React form, bind its value to component state and provide option elements. section 9.2.5

Choose the pattern that matches the selection:

  • For a single selection, set the select element’s value from state and update that state in its change handler. section 9.2.5
  • For multiple selections, store selected values in an array and collect them from the selected options; this takes extra handling. section 9.2.5

Task priority

Keep the task’s priority in form state, connect it to a select element, and update it when the user chooses an option. section 9.2.5

Listing 9.11 The form component with a drop-down (excerpt)
import { useState } from "react";
function Add({ handleAdd, handleCancel }) {
  const [data, setData] = useState({
    title: "",
    priority: "low",                                #1
  });
  const onChange = (evt) => {                       #2
    const key = evt.target.name;                    #2
    const value = evt.target.value;                 #2
    setData((oldData) =>                            #2
      ({ ...oldData, [key]: value }));              #2
  };                                                #2
  ...
      <label>
        Priority:
        <select
          value={data.priority}                     #3
          name="priority"                           #3
          onChange={onChange}                       #3
        >
          <option value="low">Low</option>          #4
          <option value="medium">Medium</option>    #4
          <option value="high">High</option>        #4
          <option value="urgent">Urgent</option>    #4
        </select>
      </label>
  ...

See a form example that connects a priority select to state and a change handler. section 9.2.5

How React Quickly, Second Edition covers it

How deep it goes
Explains controlled single-select values and option elements, then outlines multiselect state and selected-option extraction.
Examples
Uses task priority, a multiselect list of people, and an administrator choosing which user’s dashboard to view.
What you can do after
Build it from scratch by binding a select to state and updating the chosen task priority.
How it connects
Connects select elements to React state, form event handlers, and context-driven dashboards.

Also explained in

Compare how 10 books explain dropdown →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Quickly, Second Edition. The section links point to the parts of the book it draws on.