Home > database >  how to write a handler for multiple checkboxes in a functional component?
how to write a handler for multiple checkboxes in a functional component?

Time:04-21

if I have such form in Class component

<input type="text" name="address" onChange={this.onChange} value={this.state.address} />
<input type="text" name="description" onChange={this.onChange} value={this.state.description} />

I can use a handler like this to handle them

onChange (e) {
   this.setState({ [e.target.name] : e.target.value});
}

How can I do the same in functional component where I have functions like setAdress, setDescription ?
i.e can I somehow write one handler to handle multiple checkboxes

thanks in advance

CodePudding user response:

Yes, you can write one handler to handle multiple checkboxes, by putting all states in the same useState. E.g. const [state, setState] = useState({adress: "", description: ""}). Then just use e.target.name to figure out which part to change:

setState({...state, [e.target.name]: e.target.value});

CodePudding user response:

const [address, setAddress] = useState();

const [description, setDescription] = useState();

    <input
  type="text"
  name="address"
  onChange={(e) => setAddress(e.target.value)}
  value={address}
/>
<input
  type="text"
  name="description"
  onChange={(e) => setDescription(e.target.value)}
  value={description}
/>

Another Methods

const [values, setValues] = useState({
    address: "",
    description: "",
  });

  const handleChange = (e) => {
    setValues({ ...values, [e.target.name]: e.target.value });
  };

  console.log(values);

<input
  type="text"
  name="address"
  onChange={handleChange}
  value={values.address}
/>
<input
  type="text"
  name="description"
  onChange={handleChange}
  value={values.description}
/>
  • Related