botana_dev
botana_dev

Reputation: 518

React onChange: Can I make a handleChange for many onChange events, and also pass an object key as a parameter?

SOLUTION

const onChangeHandler = (e, name) => {
  setFormData((c) => ({
    ...c,
    [name]: e.target.value,
  }));
};

onChange={(e) => onChangeHandler(e, "firstName")}

OLD

I have this function inside some inputs. There are like 15 inputs. I was wondering if I could wrap them up in a function and handle them all together. My individual input onChange handler is the following:

onChange={({ target }) =>
  setFormData((c) => ({
    ...c,
    driversLicense: target.value,
  }))
}

setFormData is passed from another component as props. Takes the previous value (c) and adds our current value. I would like a function to set dynamically the key and the target. So something like that, but I can't even reach the name. It says that it's not used. Any ideas?

const onChangeHandler = (e, name) => {
  setFormData((c) => ({
    ...c,
    name: e.target.value,
  }));
};

Upvotes: 0

Views: 735

Answers (1)

tokland
tokland

Reputation: 67860

You need { [propertyNameFromVariable]: value }:

const onChangeHandler = (e, name) => {
  setFormData((c) => ({
    ...c,
    [name]: e.target.value,
  }));
};

(The next question would be: how do we memorize this with useMemo/useCallback?)

Upvotes: 1

Related Questions