guest381
guest381

Reputation: 185

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

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

Upvotes: 0

Views: 56

Answers (2)

Vinoth Smart
Vinoth Smart

Reputation: 403

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}
/>

Upvotes: 1

Emil Karlsson
Emil Karlsson

Reputation: 1078

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});

Upvotes: 2

Related Questions