AI Hints
React · Lesson 26 of 120

Several Inputs

One state object.

⏱ 2 min read▶ Video at 20:28🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

A form with many fields can keep them all in one state object. One change handler can update any field, using the input's name.

  • Many fields
  • One object
  • One handler

One handler for all

Form state holds the name, email, and city. Each input has a name attribute matching its field. Handle change copies the form, and sets the field with that name. We fill in two fields. Run it.

App.jsxjsx
import { useState } from "react";

export default function App() {
  const [form, setForm] = useState({ name: "", email: "", city: "Leeds" });

  const handleChange = e => setForm({ ...form, [e.target.name]: e.target.value });

  return (
    <div>
      <input id="n" name="name" value={form.name} onChange={handleChange} placeholder="Name" />
      <input id="e" name="email" value={form.email} onChange={handleChange} placeholder="Email" />
      <input name="city" value={form.city} onChange={handleChange} />
      <pre>{JSON.stringify(form, null, 2)}</pre>
    </div>
  );
}
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}
Also uses actions.json
[{"type": "#n", "text": "Sam"}, {"type": "#e", "text": "sam@example.com"}]

Summary

One state object and one handler can run a whole form, using each input's name. Next, checkboxes and selects.

Key takeaways
  • useState({...})
  • name attribute
  • [e.target.name]
Next up: Checkboxes and Selects — other inputs