React / React Forms / Multiple Inputs
Home /React /React Forms /Multiple Inputs

Multiple Inputs

Handling Multiple Inputs

Managing a separate state variable for every input becomes unwieldy in large forms. The standard pattern is to use a single object in state, keyed by the name attribute of each input.

JSX — RegisterForm.jsx

import { useState } from 'react';

const initialState = {
  username: '',
  email:    '',
  password: '',
  age:      '',
};

function RegisterForm() {
  // Single state object for all fields
  const [formData, setFormData] = useState(initialState);

  // One universal handler using computed property key [name]
  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
    // Spread prev to avoid mutation; [name] is a computed key
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(formData); // { username, email, password, age }
    setFormData(initialState); // Reset after submit
  };

  return (
    <form onSubmit={handleSubmit}>
      <input name="username" value={formData.username}
             onChange={handleChange} placeholder="Username" />
      <input name="email"    value={formData.email}
             onChange={handleChange} type="email" placeholder="Email" />
      <input name="password" value={formData.password}
             onChange={handleChange} type="password" placeholder="Password" />
      <input name="age"      value={formData.age}
             onChange={handleChange} type="number" placeholder="Age" />
      <button type="submit">Register</button>
    </form>
  );
}

export default RegisterForm;

The spread ...prev ensures immutability, you create a new object instead of mutating the existing state. React compares by reference, so mutating directly means no re-render.