Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
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,
  }));
};
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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?)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!