CodeBlanks Logo Icon CodeBlanks

Multiple fields

Learn to manage several form fields with one state.

Multiple fields

The cleanest way to manage two or three fields is one object state: const [form, setForm] = useState({name: "", email: ""}).

You write a single handleChange and update using the field name. This cuts code repetition.

Later React Hook Form automates this; for now we learn the base.

Single handler approach

You give each input a name attribute and update by field name in one handler: setForm(f => ({...f, [e.target.name]: e.target.value})).

Here [e.target.name] is a computed property; it names the field dynamically. We will see this form later.

This approach means even a ten-field form needs only one handler.

Practice Two-field form

Complete the skeleton. Write a SignupForm component; import useState. Define const [form, setForm] = useState({name: "", email: ""});. Return a <form> with two inputs: one value={form.name}, the other value={form.email}. Export it.

Starter code

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

// Define SignupForm here

Sample solution

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

function SignupForm() {
  const [form, setForm] = useState({ name: "", email: "" });
  return <form><input value={form.name} /><input value={form.email} /></form>;
}

export default SignupForm;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the cleanest way to hold two fields?

App.jsx
Object state updates with spread.
  • A single object useState Correct answer
  • Two separate props
  • Two separate useState
  • A global variable

Explanation: Related fields group into one object.

2 Multiple fields: fill in the missing part

Question
setForm(f => ({ ...f, email: ____ }))
Answer
setForm(f => ({ ...f, email: e.target.value }))

Explanation: You wrote the email field with the current text.

3 Multiple fields: match the terms

Term Meaning
name attribute Field name
[e.target.name] Computed property
...f Old fields
setForm Object updater

All lessons in Beginner