Skip to content
ClapelloNotes by Barath
ReactCh 14 · 4/6
Core4 min readUpdated

React / 79

Controlled forms with many fields

TL;DR

Text, textarea, select, checkbox and radio all follow one pattern, value from state and onChange back to state. One object and one handler can run a whole form.

Every field type in one table

FieldControl it withRead it in onChange
<input> (text, email, number…)valuee.target.value (always a string)
<textarea>value (not children)e.target.value
<select>value on the <select>e.target.value
<input type="checkbox">checkede.target.checked (a boolean)
<input type="radio">checked={choice === "x"} plus value="x"e.target.value

The rule never changes: state goes in, onChange sends the new value back to state. Only the prop name differs.

One state object, one handler

Instead of five useState calls, keep the form in one object. Give each input a name that matches its key, and one handler can update any of them:

1 · the user picks

<select name="size">chooses "large"
onChange={handleChange}

2 · read e.target

name: "size" value: "large"
computed key

3 · update one key

setForm({ ...form, [name]: value })
re-render

4 · new state

{ …, size: "large" }
The input's name says which key to update. One handler and one state object serve every field, because [name] picks the key at run time.
OrderForm.jsx
import { useState } from "react";
 
export default function OrderForm() {
  const [form, setForm] = useState({
    name: "",
    notes: "",
    size: "regular",
    extraCheese: false,
    delivery: "home",
  });
 
  function handleChange(e) {
    const { name, value, type, checked } = e.target;
    setForm({ ...form, [name]: type === "checkbox" ? checked : value });
  }
 
  function handleSubmit(e) {
    e.preventDefault();
    console.log("Order:", form);
  }
 
  // return ( …see the JSX tab… );
}
OrderForm.jsx (return)
return (
  <form onSubmit={handleSubmit}>
    <label>Name <input name="name" value={form.name} onChange={handleChange} /></label>
    <label>Notes <textarea name="notes" value={form.notes} onChange={handleChange} /></label>
    <label>
      Size
      <select name="size" value={form.size} onChange={handleChange}>
        <option value="small">Small</option>
        <option value="regular">Regular</option>
        <option value="large">Large</option>
      </select>
    </label>
    <label>
      <input type="checkbox" name="extraCheese" checked={form.extraCheese} onChange={handleChange} />
      Extra cheese
    </label>
    <label>
      <input type="radio" name="delivery" value="home" checked={form.delivery === "home"} onChange={handleChange} />
      Home delivery
    </label>
    <label>
      <input type="radio" name="delivery" value="pickup" checked={form.delivery === "pickup"} onChange={handleChange} />
      Pickup
    </label>
    <button type="submit">Place order</button>
  </form>
);

Two pieces of JavaScript make the handler work:

  • [name]: … is a computed property name. The key is whatever string name holds, so name="size" updates form.size.
  • { ...form, … } copies every other field. State objects must be replaced, never changed in place (see updating objects and arrays).

A controlled form, live

Try it
Delivery

const [form, setForm] = useState(…)

{
  "name": "",
  "notes": "",
  "size": "regular",
  "extraCheese": false,
  "delivery": "home"
}

Type, pick and tick. Every change goes through one handleChange and lands in one state object, shown on the right as JSON.

Submitting

Put the submit logic on the form's onSubmit, not on the button's onClick. The browser fires submit when the user clicks a submit button or presses Enter in a text field, so both paths go through one function. Call e.preventDefault() first, or the browser reloads the page.

Don't

onClick on the button

<div>
  <input value={form.name} onChange={handleChange} name="name" />
  <button onClick={save}>Place order</button>
</div>

Enter does nothing, and native checks like required never run, because there's no form to submit.

Do

onSubmit on the form

<form onSubmit={handleSubmit}>
  <input value={form.name} onChange={handleChange} name="name" />
  <button type="submit">Place order</button>
</form>

Click or Enter, it's the same handleSubmit.

Does every form need to be controlled?

No. A controlled form re-renders on every keystroke, which is fine for normal forms and gives you live previews, counters and validation. If you only need the values once, on submit, you can skip state and read them with FormData (two topics ahead). For very large forms, teams often use a library such as React Hook Form, which leans on uncontrolled inputs to avoid the re-renders.

Gotchas

Recall

Can you answer these?

0/5

Answer out loud (or in your head) before you tap. That's what makes it stick.

Saved on this device only. No login.