-1

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 ReactJS?

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");
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Rohit Verma
  • 3,657
  • 7
  • 37
  • 75
  • 1
    Does this answer your question? [How to create a JavaScript callback for knowing when an image is loaded?](https://stackoverflow.com/questions/280049/how-to-create-a-javascript-callback-for-knowing-when-an-image-is-loaded) – Konrad Dec 19 '22 at 18:20
  • There is even an `onLoad` prop – Konrad Dec 19 '22 at 18:20
  • wrap your image with a `new window.Image()` and attach an `onLoad()` listener. – Gonras Karols Dec 19 '22 at 18:21

1 Answers1

0

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>;
};
Uzair Ashraf
  • 1,171
  • 8
  • 20