How to Handle Multiple Inputs in React: Simple and Correct Approach
useState object to store all input values and one onChange handler that updates the state based on the input's name attribute. This keeps your code simple and scalable for forms with many fields.Why This Happens
When handling multiple inputs, beginners often create separate state variables and handlers for each input. This leads to repetitive code and difficulty managing many inputs. Also, using incorrect event handlers or not linking inputs to state causes inputs not to update properly.
import React, { useState } from 'react'; function Form() { const [firstName, setFirstName] = useState(''); const [lastName, setLastName] = useState(''); return ( <form> <input type="text" value={firstName} onChange={e => setFirstName(e.target.value)} placeholder="First Name" /> <input type="text" value={lastName} onChange={e => setLastName(e.target.value)} placeholder="Last Name" /> <p>First Name: {firstName}</p> <p>Last Name: {lastName}</p> </form> ); } export default Form;
The Fix
Use a single state object to hold all input values. Assign each input a name attribute matching its key in state. Use one onChange handler that updates the correct field by reading event.target.name and event.target.value. This reduces repetition and keeps inputs in sync.
import React, { useState } from 'react'; function Form() { const [inputs, setInputs] = useState({ firstName: '', lastName: '' }); const handleChange = (event) => { const { name, value } = event.target; setInputs(prev => ({ ...prev, [name]: value })); }; return ( <form> <input type="text" name="firstName" value={inputs.firstName} onChange={handleChange} placeholder="First Name" /> <input type="text" name="lastName" value={inputs.lastName} onChange={handleChange} placeholder="Last Name" /> <p>First Name: {inputs.firstName}</p> <p>Last Name: {inputs.lastName}</p> </form> ); } export default Form;
Prevention
Always use a single state object for multiple related inputs to keep your code clean and easy to maintain. Give each input a unique name attribute that matches the state key. Use one generic onChange handler to update state dynamically. This pattern prevents bugs and repetition.
Use linting tools like ESLint with React plugin to catch common mistakes. Also, consider controlled components for predictable input behavior.
Related Errors
1. Inputs not updating: Happens if you forget to set value from state or don't update state on change.
2. State overwriting: Occurs if you replace the whole state object instead of merging updates, losing other input values.
3. Missing name attribute: The handler can't identify which input changed, so state won't update correctly.