1

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.

Ashmita Singh
  • 69
  • 2
  • 2
  • 11
  • How about putting all of your fields in one useState hook? Then do it as you were doing on the class base component state? – Ryan Le Aug 08 '21 at 07:46
  • I mean like this: const [fields, setFields] = useState({newColorName: '', newPaltetteName: ''}); – Ryan Le Aug 08 '21 at 07:47

1 Answers1

1

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.