React Forms: Handle Multiple Input Fields with useState
Handling Multiple Input Fields
The Problem
A signup form with five fields does not need five separate useState calls and five separate handlers. That gets repetitive fast.
The Solution: One Object, One Handler
Store all fields in a single state object and write one handler that uses the input's name attribute to decide which field to update.
Example
src/components/RegistrationForm.jsx
jsx
import { useState } from "react";
function RegistrationForm() {
const [formData, setFormData] = useState({
fullName: "",
email: "",
course: "react",
agreeToTerms: false
});
function handleChange(event) {
const { name, value, type, checked } = event.target;
setFormData(prevData => ({
...prevData,
[name]: type === "checkbox" ? checked : value
}));
}
function handleSubmit(event) {
event.preventDefault();
console.log("Submitted:", formData);
}
return (
<form onSubmit={handleSubmit}>
<input
type="text"
name="fullName"
value={formData.fullName}
onChange={handleChange}
placeholder="Full name"
/>
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
placeholder="Email address"
/>
<select name="course" value={formData.course} onChange={handleChange}>
<option value="react">React Development</option>
<option value="node">Node.js Backend</option>
<option value="fullstack">Full Stack</option>
</select>
<label>
<input
type="checkbox"
name="agreeToTerms"
checked={formData.agreeToTerms}
onChange={handleChange}
/>
I agree to the terms
</label>
<button type="submit">Register</button>
</form>
);
}
export default RegistrationForm;How It Works
- Each input has a name that matches a key in formData.
- const { name, value, type, checked } = event.target; destructures what the handler needs.
- [name]: ... is a computed property name. The square brackets mean "use the value of the name variable as the key". Without them, you would literally create a key called "name".
- Checkboxes use checked instead of value, which is why the handler checks type.
- setFormData(prevData => ({ ... })) uses the functional form. The extra parentheses around the object are required without them, JavaScript reads { as the start of a function body.
- event.preventDefault() in handleSubmit stops the browser's default page reload.
Note on select and checkbox
Input type | Controlled by |
| text, email, password, textarea | value |
| select | value on the <select> element, not on <option> |
| checkbox | checked |
| radio | checked, with all buttons sharing a name |
In React, <textarea> uses value rather than inner text, and <select> uses value rather than the selected attribute on an option.
Output
Typing in any field updates the shared state object. Submitting logs the complete form data and does not reload the page.
ReactJS Tutorial
Vishalini A








