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

85
Visualizações
I am unable to use array elements in src attribute of img tag in React

I aim to render multiple images whose path I have already defined in an array called images. But when I want to use it in the src attribute of an img tag, for some reason it does not renders the image, even though the path is correct.

The code that I wrote in the react component was as follows:

let images=["../../../assets/temp.jpg", "../../../assets/temp2.jpg", "../../../assets/temp3.jpg"];
let n = images.length;
let imgArray = [];

for (let i = 0; i < n; i++) {
    imgArray.push(<img src={images[i]} alt="image cover" />);
}
return(
    <div>
        {imgArray}
    </div>
);

The above code does not render the image provided as a path in src. But if I import the path and then provide that imported element as the src, then it works fine.

The tech I have used in my project is React.js and Bootstrap

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

0

React uses JSX which cannot display arrays. In your code {imgArray} is an array of images, which you now need to loop through and convert to a JSX component/element.

The best approach is to use the array.map function built in to JS arrays. ​

// use "const" not let if the var doesn't change
const imgArray = [
    {
        key: 'uniqueid1',
        src: 'path/to/img.png',
    },
];

return
   ​<div>
       ​{
            imgArray.map(_img => <img 
                src={_img.src} 
                key={_img.key}
                alt="image cover" 
            />)
        }
  ​</div>
);

You'll note we now don't need the for loop either.

PS: Don't forget the "key" it's very important for React to reconcile the image elements you have created (and don't use the array index either)

More info:

  • List and Keys
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