Ashmita Singh
Ashmita Singh

Reputation: 69

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.

Upvotes: 1

Views: 1755

Answers (1)

Yashwanth somayajula
Yashwanth somayajula

Reputation: 178

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.

Upvotes: 1

Related Questions