How to handle multiple form fields in React

Handling multiple form fields efficiently requires managing all form data in a single state object with dynamic property updates for clean and scalable forms. As the creator of CoreUI, a widely used open-source UI library, I’ve built complex form systems for enterprise applications with dozens of form fields and validation. From my expertise, the most effective approach is using a single state object with computed property names for dynamic updates. This method reduces code duplication and provides centralized form state management with consistent update patterns.

Use a single state object with dynamic property names to handle multiple form fields efficiently.

import { useState } from 'react'

function MultiFieldForm() {
  let [formData, setFormData] = useState({
    firstName: '',
    lastName: '',
    email: '',
    phone: '',
    address: ''
  })

  let handleInputChange = (event) => {
    let { name, value } = event.target
    setFormData(prevData => ({
      ...prevData,
      [name]: value
    }))
  }

  let handleSubmit = (event) => {
    event.preventDefault()
    console.log('Form Data:', formData)
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        name="firstName"
        value={formData.firstName}
        onChange={handleInputChange}
        placeholder="First Name"
      />
      <input
        name="lastName"
        value={formData.lastName}
        onChange={handleInputChange}
        placeholder="Last Name"
      />
      <input
        name="email"
        type="email"
        value={formData.email}
        onChange={handleInputChange}
        placeholder="Email"
      />
      <button type="submit">Submit</button>
    </form>
  )
}

The handleInputChange function uses object destructuring to get the name and value from the event target, then updates the specific property using computed property syntax [name]: value. The spread operator preserves existing form data while updating only the changed field.

Best Practice Note:

This is the same multi-field form approach we use in CoreUI React components for efficient state management. Use the name attribute on inputs to match your state object properties for automatic updates.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author