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

137
Vistas
react onchange push values to objects

I have an dynamic created fields (input tag)

const [data, setData] = useState({ native: [{}], rolls: [{}] }) // initial data

{navtive?.map((item, index) => {
    return (
        <input
        type="text"
        name={item.id}
        onChange={(e) =>
            handleChange("fee", e.target.value, index, item.id)
        }
        />
...
{rolls?.map((item, index) => {
    return (
        <input
        type="text"
        name={item.id}
        onChange={(e) =>
            handleChange("fee", e.target.value, index, item.id)
        }
        />

Expected Output:

const output = {
    native: [{id: 1, fee: "12"}, {id: 5, fee: "2"}],
    rolls: [{id: 4, fee: "1332"}],
};

onChange function :

const handleChange = (field, value, index) => {
    setData((prevState) => {
        const nextState = [...prevState];
        nextState[index][field] = value;
        return nextState;
    });
};

How to get the expected output ? What am I making wrong in the onChange function.

Thank you

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You must add more arguments to handleChange for this output. type - to understand what property is native or rolls. id - id from current data element. Example - sandbox

const handleChange = (type, field, value, index, id) => {
    setData((prevState) => {
      const nextState = [...prevState[type]];
      nextState[index] = {
        ...prevState[type][index],
        id,
        [field]: value
      };
      return {
        ...prevState,
        [type]: nextState
      };
    });
  };

JSX

handleChange("native", "free", e.target.value, index, item.id)
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