简体   繁体   中英

How to run a function onLoad of an image in NextJS Image component

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"}
  />
)}

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"
/>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM