Search code examples
javascriptreactjslazy-loading

react-lazy-load-image-component is not working as expected


I'm trying to lazy load images using react-lazy-load-image-component. But it is making all the images load at once.

Here's how it looks in the network tab

Here's my code

import { useState, useEffect } from 'react'
import { LazyLoadImage } from 'react-lazy-load-image-component';
import 'react-lazy-load-image-component/src/effects/blur.css';

function App() {
  const [images, setImages] = useState([]);
  const url = "https://api.unsplash.com/photos/?client_id=9MRdzVycZVHXD5HX93lbynQl8ZCj3_rrV5LSJSuEp4o&query=nature&per_page=30";

  useEffect(() => {
    fetch(url)
    .then(res => res.json())
    .then(data => setImages(data))
  }, [])

  return (
    <>
      <div style={{display: "grid", gridTemplateColumns: "repeat(4, 1fr)"}}>
        {
          images.map(image => (
            <LazyLoadImage
            loading='lazy'
            effect='blur'
            src={image.urls.regular}
            alt={image.alt_description} key={image.id}
            width="100%" />
          ))
        }
      </div>
    </>
  )
}

export default App

Solution

  • You need to make sure you either set height and width props or a placeholder to your images, that should help with the problem, since all the images are size 0 x 0 when loading, making all visible and then load them all at once.