Topic 23 of 54
Handling Multiple Inputs
Overview
If you have a form with 10 fields (Name, Email, Password, Address, etc.), creating 10 separate `useState` hooks and 10 separate `onChange` functions is incredibly tedious and unscalable. Instead, you can use a single state object to hold all the form data, and write one dynamic `handleChange` function that handles every input automatically.
Syntax
By giving each input a `name` attribute that exactly matches a key in our state object, we can use `[name]: value` to update the correct field dynamically.
Dynamic State Management
jsx
import { useState } from 'react';
function SignupForm() {
// 1. One state object for all fields
const [formData, setFormData] = useState({
firstName: "",
lastName: "",
email: ""
});
// 2. A single dynamic handler
const handleChange = (e) => {
const { name, value } = e.target;
// 3. Compute the property name dynamically using bracket notation
setFormData(prevData => ({
...prevData,
[name]: value
}));
};
return (
<form>
{/* The 'name' attribute MUST exactly match the state key */}
<input name="firstName" value={formData.firstName} onChange={handleChange} />
<input name="lastName" value={formData.lastName} onChange={handleChange} />
<input name="email" value={formData.email} onChange={handleChange} />
</form>
);
}Common Pitfalls
- Forgetting to spread the old state `...prevData`. If you omit it, typing in the 'lastName' field will instantly delete the 'firstName' and 'email' fields from state!
- A mismatch between the input's `name` attribute and the state key. They must be identical.
Interview Tips
- Mastering the dynamic `[name]: value` syntax shows you understand advanced JavaScript object properties (computed property names).
Real-World Example
Handling different input types (like checkboxes which use `checked` instead of `value`).
example
jsx
const handleChange = (e) => {
const { name, value, type, checked } = e.target;
// Checkboxes use the 'checked' property, text inputs use 'value'
const finalValue = type === "checkbox" ? checked : value;
setFormData(prev => ({
...prev,
[name]: finalValue
}));
};