MyInternships.in

State & Events

React Handling Multiple Inputs

Instead of one useState per field, keep the whole form in a single object and write one change handler that uses the input’s name attribute as the key. Adding a field then needs no new state and no new handler.


What is Handling Multiple Inputs in React?

Instead of one useState per field, keep the whole form in a single object and write one change handler that uses the input’s name attribute as the key. Adding a field then needs no new state and no new handler.

Why Handling Multiple Inputs matters

A registration form with eight fields becomes eight useState calls and eight handlers. One object plus one handler keeps it to two.

Handling Multiple Inputs example

One handler for every field
JSX
const [form, setForm] = useState({ name: '', email: '', city: '', agree: false });

function handleChange(e) {
  const { name, value, type, checked } = e.target;
  setForm(prev => ({ ...prev, [name]: type === 'checkbox' ? checked : value }));
}

<input name="name"  value={form.name}  onChange={handleChange} />
<input name="email" value={form.email} onChange={handleChange} />
<input name="agree" type="checkbox" checked={form.agree} onChange={handleChange} />

How this works

The computed key [name] writes to whichever field fired the event. The type check handles checkboxes, whose meaningful value is checked rather than value.

Key points to remember

  • Every input needs a name attribute that matches its key in state.
  • Use the functional setter so rapid typing never drops an update.
  • Reset the whole form by setting it back to the initial object.

Common mistakes with Handling Multiple Inputs

  • Forgetting the name attribute, so [name] becomes an "undefined" key.
  • Reading e.target.value for a checkbox, which is the literal string "on".

React Handling Multiple Inputs— Interview Questions & FAQs

How do I handle many form inputs without repeating code?+

Store the form as one object and write a single handler keyed on e.target.name. Each input then needs only name, value and the shared onChange.

Related React Topics

Keep learning with these closely related lessons.

Ready to use your React skills?

Find verified React internships and fresher developer jobs across India.

Browse React Internships