Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

163
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda