React Multiple Inputs

React Multiple Inputs

When you need to handle multiple controlled input elements within a single form component, you can add a name attribute to each element and let the unified handler function intelligently choose what to do based on the runtime value of event.target.name.

Handling Multiple Inputs

import { useState } from 'react';

function Form() { const [inputs, setInputs] = useState({}); const handleChange = (e) => { const { name, value } = e.target; setInputs(values => ({...values, [name]: value})); }; return <input name="username" value={inputs.username || ""} onChange={handleChange} />; }