Tuesday, May 10, 2022

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

Issue

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

Solution

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



Answered By - stickyuser
Answer Checked By - Cary Denson (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.