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

353
Visualizações
onChange event inside loop is only passing 0th index

The following code is a input component which uploads an image and I am using a function "handleImageChange" to trigger onChange event. it is inside a loop

{images.map((x,i) => (
    <Grid item>
           <Input
              accept="image/*"
              id="change-image-file"
              required
              type="file"
              onChange={(e) => handleImageChange(e, i)}
           />
    </Grid>
)}

 const handleImageChange = (e, index) =>{
       conole.log(index)   // whichever index I click it always returns 0
       conole.log(e.target.files[0])  // however e.target.value works alright
 }

this is the image in correspondence with the code where I am clicking the 2nd image button but still getting the index 0

I am using React 18, Material UI 5, and the "Input" & "Grid" is from material UI which resembles HTML "input" & "div" respectively.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

move your <Grid> outside map and than try


<Grid item>
     {images.map((x,i) => (

           <Input
              accept="image/*"
              id="change-image-file"
              required
              type="file"
              onChange={(e) => handleImageChange(e, i)}
           />
     )}
</Grid>
about 4 years ago · Juan Pablo Isaza Relatório

0

As Aman suggests, first move your Grid outside loop. Second thing you should change is that you need to provide dynamic key and id to each element, like this you declare same id to each element and no key at all - React core principle relays on keys when working with loop that outputs component instances.

You should try something like this:

<Grid item>
 {images.map((x,i) => (

       <Input
          key={`k-${i}`}
          id={`i-${i}`}
          accept="image/*"
          required
          type="file"
          onChange={(e) => handleImageChange(e, i)}
       />
 )}
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