← React Foundations
10 / 25
Lesson 10 — Multi-field form
One state object for a whole form
Instead of one useState per field, keep the form in one object and give each input a name attribute that matches its key. One handler copies the object with spread and overwrites just that key. [key]: value in an object literal is a computed property name — it uses the variable's value as the key.
const key = "city";
const next = { ...form, [key]: "Oslo" }; // same as { ...form, city: "Oslo" }
Why it matters: sign-up and checkout forms have many fields; this keeps them to one handler.
Want it another way?
Task
Make update copy f and change only the field named by e.target.name. Typing Sam and Oslo should show "Sam from Oslo".
Test your knowledge
A quick 3-question quiz on this lesson — instant feedback.