Home > other >  How to preload images in React?
How to preload images in React?

Time:06-04

I have an array of images, e.g.

var imgsArray = [];
imgsArray[0] = new Image();
imgsArray[0].src = "https://upload.wikimedia.org/wikipedia/commons/b/b6/Queen_Elizabeth_II_in_March_2015.jpg";
imgsArray[1] = new Image();
imgsArray[1].src = "https://upload.wikimedia.org/wikipedia/commons/b/b6/Queen_Elizabeth_II_in_March_2015.jpg";

I would like to add the images in this array to the JSX returned by a React component. How do I do this?

I tried the following:

<ImageList cols={1}>
  {imgsArray.map((img) => (
    <ImageListItem key={img.src}>
      img
    </ImageListItem>
</ImageList>

But no images appeared, nor did any errors appear.

I also tried placing curly braces around img i.e. {img} and received the error Uncaught Error: Objects are not valid as a React child (found: [object HTMLImageElement]). If you meant to render a collection of children, use an array instead.

CodePudding user response:

Instantiating the element and setting the src property is enough to start preloading the image, there is no need to attach it to the DOM.

const images = ['someImageUrl.jpg', 'someOtherImageUrl.jpg'];

for (const image of images) {
  const imageElement = new Image();
  imageElement.src = image;
}

<ImageList>
  {images.map((img) => (
    <ImageListItem key={img}>
      <img src={img} />
    </ImageListItem>
  ))}
</ImageList>
  • Related