'How should I implement lazy loading for my images in react?

I'm trying to add lazy loading to my react application as I have over 200 images that I don't need on the initial load. If I lazy load the images, does this mean, they won't be loaded until they're needed on the screen?

I'm currently importing 4 groups of about 50 images into .js files and then adding them to objects so they can be dynamically used in my components. It looks like this...

// SportImages.js file
import Football from './images/football.png
import Cricket from './images/cricket.png
import Soccer from './images/soccer.png
... // another 50 or so imports

export default {
  Football,
  Cricket,
  Soccer,
  ... // another 50 or so files
}

// and then in my component
cards.map(x => {
  return (
    <img src={SportImages[x.image_ref]} />
  )
})

So my question is, should I be using lazy loading in the component file or in the main images file if I want to lazy load every image?



Solution 1:[1]

You can add the loading attribute to your image element to lazy-load the images. A complete explainer guide on this attribute can be found on web.dev.

In your case it would probably look as follows:

cards.map(card => (
  <img src={SportImages[card.image_ref]} loading="lazy" />
))

Solution 2:[2]

You can use this library called react-lazy-load-image-component Import the LazyLoadImage component then use it the render you images

cards.map(card => (
     <LazyLoadImage src={SportImages[card.image_ref]} {...props}/>
  ))

You can also add an effect when lazy loading the images. You can check the documentation of the library here https://www.npmjs.com/package/react-lazy-load-image-component

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jon Koops
Solution 2 Gab Agoncillo