简体   繁体   中英

how to check image fully loaded in react js?

How to check image fully loaded or not. Actually a image coming from API I want to check image height so i'm unable to check image height because image is talking time to load how to check it in react js?

My Code:-

 export const App = () => { const [imgHeight, setImgHeight] = useState(0); var myImage = document.getElementById("myImg"); var isImgLoaded = myImage.complete && myImage.naturalHeight;== 0? setImgHeight(isImgLoaded. myImage.getBoundingClientRect():height; "not loaded"); }

Thanks for your efforts!

Instead of querying the DOM and checking to see if the image has loaded, why not create a helper function that preloads the image and set state to update it.

export const App = () => {
  const imageSrc = "my url";
  const [isImgLoaded, setImgLoaded] = useState(false);
  const preloadImage = (src) => {
    return new Promise((resolve, reject) => {
      const img = document.createElement("img");
      img.onload = resolve;
      img.onerror = reject;
      img.src = src;
    });
  };

  useEffect(() => {
    (async () => {
      try {
        await preloadImage(imageSrc);
        setImgLoaded(true);
      } catch (error) {
        console.error(error);
      }
    })();
  }, []);
  return isImgLoaded && <div>Success!</div>;
};

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