9

I want to show a skeleton while my image is loading. I tried to pass an onLoad prop in the new Image component provided by NextJS but the function fires off before the image is loaded.

Here is my code

const [loaded, setLoaded] = useState(false);

<Image
  src={src}
  alt={""}
  className={styles.image_tag}
  onLoad={(e) => setLoaded(true)}
  style={{ opacity: loaded ? "1" : "0" }}
  layout={"fill"}
/>

{!loaded && (
  <Skeleton
    className={styles.skeleton}
    variant={"rect"}
    animation={"wave"}
  />
)}
Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57
angelo
  • 2,661
  • 3
  • 16
  • 22

2 Answers2

4

You could can use the onLoad prop like so:

Referenced from https://github.com/vercel/next.js/discussions/20155

const [isImageReady, setIsImageReady] = useState(false);

const onLoadCallBack = (e)=>{
   setIsImageReady(true)
   typeof onLoad === "function" && onLoad(e)
}

return(
  <div>
   {!isImageReady && 'loading image...'}
   <Image 
     onLoad={onLoadCallBack} 
     src={'/'+image} 
     alt={title} 
     width={260}  
     height={160} />
  </div>
)

******************************* UPDATE *****************************

Nextjs now provides a placeholer and blurDataURL prop with which you can show an image placeholder before the main image is loaded.

An example


<Image
 className="image"
 src={image.src}
 alt={image.alt}
 layout="fill"
 objectFit="cover"
 objectPosition="top center"
 placeholder="blur"
 blurDataURL="/images/blur.jpg"
/>

Dev_Ose
  • 51
  • 4
3

As of 11.1 you can use onLoadingComplete

A callback function that is invoked once the image is completely loaded and the placeholder has been removed.

https://nextjs.org/docs/api-reference/next/image#onloadingcomplete

stickyuser
  • 2,552
  • 15
  • 15