arga wirawan
arga wirawan

Reputation: 237

'load' event listener for detect image is done loaded is not working in react

I try to console some message when image is fully loaded using 'load' listener, but the code did not work, how to properly write a 'load' event listener in react ? Thankyou

  useEffect(() => {
  window.addEventListener('load', (event) => {
   const imageTest = document.querySelector('img')
   const isLoaded = imageTest.complete && imageTest.naturalHeight !== 0
   console.log(isLoaded)
  })

  }, [])

Upvotes: 2

Views: 2436

Answers (2)

arga wirawan
arga wirawan

Reputation: 237

The way to listen image is successfully loaded in react component is just put onLoad on your <img> tag, for example :

const MyCompoent = () => {
return <img src="yourImageLink.png" onLoad={()=>{console.log('The Image is successfully loaded')} } />
}

instead console a message you can pass a function as well

Upvotes: 0

Imran Rafiq Rather
Imran Rafiq Rather

Reputation: 8118

This is not how react works. You are trying to use load event within the component when everything else is already loaded within from <div id="root"></div>.

React is Single Page App. And for the whole document load happens once only :)

However for individual elements we can set onload and fire that event in componentDidMount() or in useEffect() Hook

UPDATE: For image load check you do something like. You can do this or even use useRef()

  useEffect(() => {
 
   const imageTest = document.querySelector('img');
       imageTest.onload = ()=>{
       // Image is loaded and your further steps :)
       const isLoaded = imageTest.complete && imageTest.naturalHeight !== 0
       console.log(isLoaded);
      }

  }, []);

There is also one more easy way to do this:

Using onLoad synthetic event right on the image element itself. Which I think should also work fine:

const ImageLoadDemo ()=> {

  const handleImageLoaded =()=> {
    console.log("Image was successfully loaded");
  }

  const handleImageErrored =()=> {
    console.log("Image was not loaded successfully");
  }


    return (
      <div>
        <img
          src="https://picsum.photos/200/300"
          onLoad={handleImageLoaded}
          onError={handleImageErrored}
        />
      </div>
    );
}

Upvotes: 3

Related Questions