ReactJs - Using single state object to handle multiple fields of form

Sometimes you may have seen reactjs form component code where a separate state variable is assigned to separate form fields and a separate onChange handler for each form field. There is no harm in this method, but it creates some extra code in your file which could create a future problem in managing the project.

However, there is a way to have a simple, just one-state object to handle data of all fields in the form. You can have a single-state object having multiple properties. Each property of this state object will be assigned to the respective form field. That is, you would bind the field's state to the property of this state object. Then you do not need to create multiple onChange handlers functions for this form. You can use the same onChange handler to handle multiple fields.

 

Herein is an example :


import React from 'react';
export default function Myform() {
   
    const [formData, setFormData] = React.useState({ name: '', email: '' });

    const handleChange = ({target:{name, value}}) => {
        setFormData({ ...formData, [name]: value });
    }

    return (<div className="MyForm">
        <h1>My Form</h1>
        <form>
            <div>
                <label htmlFor="name">Name</label>
                <input type="text" name="name" id="name" onChange={handleChange} />
            </div>
            <div>
                <label htmlFor="email">Email</label>
                <input type="email" name="email" id="email" onChange={handleChange} />
            </div>
            <div>
                <button type="submit">Submit</button>
                <button type="reset">Reset</button>
            </div>
        </form>

    </div>);
}