Multiple Inputs in React
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.
Using One State Object for Multiple Inputs
Instead of creating separate useState for every input:
const [name, setName] = useState("");
const [email, setEmail] = useState("");
- You can use one state object:
- This allows you to manage all form fields in one place.
const [form, setForm] = useState({
name: "",
email: "",
message: "",
});
Handling Multiple Inputs Dynamically
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;
- The
nameattribute of each input matches the key in the state object. [name]: valuedynamically updates the correct field....formkeeps other fields intact while updating one field.
Dynamic Select and Checkbox Fields
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 });
}
};
checkboxhandling ensures multiple options are stored in an array.selectfields can also be managed dynamically.
Advantages of This Approach
- Single source of truth: All form data in one state object.
- Scalable: Easy to add/remove fields without creating new state variables.
- Reusable:
handleChangeworks for any input type with minimal tweaks. - Easy validation: Validate the entire form object before submission.
