Careeroza
Multiple Inputs and Submit
One State Object for the Form
Example
Use the input's name to update the right field. Call e.preventDefault() so the browser does not reload the page.
import { useState } from 'react';
export default function App() {
const [form, setForm] = useState({ name: '', email: '', course: 'react', agree: false });
const [submitted, setSubmitted] = useState(null);
const handleChange = (e) => {
const { name, value, type, checked } = e.target;
setForm({ ...form, [name]: type === 'checkbox' ? checked : value });
};
const handleSubmit = (e) => {
e.preventDefault();
setSubmitted(form);
};
return (
<form onSubmit={handleSubmit}>
<input name="name" value={form.name} onChange={handleChange} placeholder="Name" />
<input name="email" value={form.email} onChange={handleChange} placeholder="Email" />
<select name="course" value={form.course} onChange={handleChange}>
<option value="react">React</option>
<option value="node">Node</option>
</select>
<label><input type="checkbox" name="agree" checked={form.agree} onChange={handleChange} /> I agree</label>
<button type="submit">Submit</button>
{submitted && <pre>{JSON.stringify(submitted, null, 2)}</pre>}
</form>
);
}Result