Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

175
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda