Search code examples
reactjsimagelazy-loading

react-lazy-load-image-component, how to hide until fully loaded?


enter image description here enter image description here

import bg from "./img/bg.png";
import react_img from "./logo.svg";

...

  <LazyLoadImage 
    effect='blur'
    src={bg}
    placeholderSrc={react_img}
    alt='stuff'
    height="200px"
    width="200px"
  />

Why is it not hiding the main image (src) completely so it can replace the placeholder? Instead it slowly comes down from top to bottom until it loads completely

I dont know why is it this way, but can you make it so it hides it completely until its fully loaded then switch it up?


Solution

  • This is because react-lazy-load-image-component sets the placeholder image as background-image, and remove it after the image is fully loaded. In the meantime, the loading main image won't be hidden, so if it's partially loaded/displayed by the browser, it will be displayed along with the placeholder image in its background.

    Fortunately, the main image's onLoad handler is triggered when the image is fully loaded. Hence, one way is to initially set the main image opacity to 0 (or zIndex to -1) and set it back using the onload handler.

    const MyImage = () => {
    
      const [imageStyle, setimageStyle] = useState({ opacity: 0 })
    
      const ImageLoad = (e) => {
        setimageStyle({})
      }
      
      return (
        <div>
          <LazyLoadImage
            src={"http://localhost:3080/large_image"}
            placeholderSrc={react_img}
            style={imageStyle}
            onLoad={ImageLoad}
          />
        </div>)
    };
    

    Alternatively, you can compress the main image's size since it's displayed 200px X 200px anyways and an image with this resolution should be loaded instantly under normal network conditions.

    ...Or, consider using a progressive image format.