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