It took me a while to figure out how to lazy load images using the excellent React Lazyload component.
The demo lazy loaded images on scroll but when testing I could not get the same behavior.
The culprit was overflow: auto;
which conflicted with the component working as intended.
What is the best way to lazy load large image gallery/slideshows in React?
React Lazyload (Really liking this component but want to investigate others)
React Virtualized (Seems heavy but feature-rich)
React Infinite (Higher barrier to entry due to complexity)
React Lazylist (Straight-forward but not sure if optimal for images)
Others...?
I have a universal/isomorphic application so some of the above will break due to window object unable to be used on the server.
If you want a simpler lazy load solution and not have to use other people's packages/code, try using the IntersectionObserver
API.
https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
I wrote a Medium article on how to use it to lazy load images in a React component (implementation is essentially the same with vanilla JS).
https://medium.com/@parkjoon94/lazy-loading-images-intersectionobserver-8c5bff730920
You only really need this part of the code (snippet from above article):
this.observer = new IntersectionObserver(
entries => {
entries.forEach(entry => {
const { isIntersecting } = entry;
if (isIntersecting) {
this.element.src = this.props.src;
this.observer = this.observer.disconnect();
}
});
}, {}
);