Clean • Professional
When building forms in React, you often have multiple input fields (text, email, password, textarea, select, etc.). Managing them individually can get messy.
A single state object for all inputs makes your code cleaner, scalable, and easier to validate.
Instead of creating separate useState for every input:
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [form, setForm] = useState({
name: "",
email: "",
message: "",
});
You can use a single handleChange function for all fields using the name attribute:
Example – Multiple Controlled Inputs
import React, { useState } from "react";
function MultiInputForm() {
const [form, setForm] = useState({
name: "",
email: "",
message: "",
});
const handleChange = (e) => {
const { name, value } = e.target;
setForm({
...form, // keep other fields unchanged
[name]: value, // update the field that changed
});
};
const handleSubmit = (e) => {
e.preventDefault();
console.log("Form Submitted:", form);
alert(`Name: ${form.name}, Email: ${form.email}, Message: ${form.message}`);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<inputtype="text"
name="name"
value={form.name}
onChange={handleChange}
/>
</label>
<br />
<label>
Email:
<inputtype="email"
name="email"
value={form.email}
onChange={handleChange}
/>
</label>
<br />
<label>
Message:
<textareaname="message"
value={form.message}
onChange={handleChange}
rows={4}
cols={40}
/>
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}
export default MultiInputForm;
name attribute of each input matches the key in the state object.[name]: value dynamically updates the correct field....form keeps other fields intact while updating one field.You can manage selects, checkboxes, and radio buttons in the same state object:
const [form, setForm] = useState({
name: "",
gender: "",
hobbies: [],
});
const handleChange = (e) => {
const { name, value, type, checked } = e.target;
if (type === "checkbox") {
const newHobbies = checked
? [...form.hobbies, value]
: form.hobbies.filter((hobby) => hobby !== value);
setForm({ ...form, hobbies: newHobbies });
} else {
setForm({ ...form, [name]: value });
}
};
checkbox handling ensures multiple options are stored in an array.select fields can also be managed dynamically.handleChange works for any input type with minimal tweaks.