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

168
Vistas
i cant access index of map function within function call on button(onClick()), which is within scope of map(),code is below

Initial State

const [variation, setVariation] = useState([
    {
      name: "",
      value: [""],
    },
  ]);

function on button click

const addValueField = (e, index) => {
    e.preventDefault();
    const field = [...variation];
    field[index].value.push("");
    setVariation(field);
  };

html render:

<div>
 {variation.map((value, index) => {
        return (
          <div className="form-control">
            <input
              key={index}
              className="bg-base-200 m-1 shadow appearance-none border rounded text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
              type="text"
              placeholder="Enter Variation Type"
            />
            <div className="form-control">
              {variation[index].value.map((value, i) => {
                return (
                  <input
                    type="text"
                    key={i}
                    className="bg-base-200 m-1 shadow appearance-none border rounded text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                    placeholder="Enter Value"
                  />
                );
              })}
              <button onClick={(e, index) => addValueField(e, index)}>
                Add another value
              </button>
            </div>
          </div>
        );
      })}
</div>

When addValueField(e,index) is called on button click, it does not pick the index of parent map(), but button is within parent map() scope, so it does not pass index to the function and error is generated.

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

0

onClick doesn't give you the index. You have to get the index from the map directly if you use as

<button onClick={(e) => addValueField(e, index)}>
  Add another value
</button>;

and you can set variation state as

const addValueField = (e, index) => {
  e.preventDefault();
  setVariation((state) =>
    state.map((o, i) => (i === index ? { ...o, value: [...o.value, ""] } : o))
  );
};
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