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...
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?
2 Answers
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