3 ms·
I know it's not the point, but you can generalize the input handler in the first example by using the name of the input field as a key — in most simple forms, a
by vcanales 4y ago
I know it's not the point, but you can generalize the input handler in the first example by using the name of the input field as a key — in most simple forms, at least:
```
const Form = () => {
const [formData, setFormData] = useState({ firstName: '', lastName: '' });
function handleChange(event) {
const { target } = event;
const { name, value } = target; // Destructuring in steps to make it easier to figure out where values come from.
setFormData({
...formData,
[name]: value
});
}
return (
<>
<input name="firstName" value={formData.firstName} onChange={handleChange} />
<input name="lastName" value={formData.lastName} onChange={handleChange} />
</>
)
}
```
- 11235813213455 4y agoeven better, wrap those props as <input {...getProps('firstName')} /> and make a custom hook returning that getProps function