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

83
Vistas
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 Respuestas
Responde la pregunta

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 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