Search code examples
reactjsreact-hooksreact-functional-componentreact-formsreact-class-based-component

Dynamic Forms - How to update the value of multiple form fields on 'onChange' event using react hooks?


Using class-based component, we do it this way for multiple input fields

handleChange(evt) {
   this.setState({
     [evt.target.name]: evt.target.value;
});

But I want to do it using hooks:

const [newName, setNewColorName] = useState('');
const [newPaletteName, setNewPaletteName] = useState('');

function handleChange(evt) {
    //For 'newColorName'
    setNewColorName(evt.target.value);
}

I know how to do it for every individual field, but I want to write a generic code just the way I did it in the class-based component, so that I don't have to repeat for each & every field.


Solution

  • It is the same way we do it with class based components, let us say we want to define a login form using hooks

    
    const [formData, setFormData] = useState({
      email: "",
      password: "",
    });
     
    onChange = e => {
     setFormData({ ...formData, [e.target.id]: e.target.value});
    }
    
    // 
    <form onSubmit={handleSubmit}>
       <input id="email" value={formData.email} onChange={handleChange} />
       <input id="password" value={formData.password} onChange={handleChange} />
       <button type="submit" />
    </form>
    
    

    The logic being we pick up an attribute like name or id in the input field corresponding to the key used in our formData, so that we can handle multiple fields using same change handler.