Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React onLoad event on image tag is not getting called when using conditional render

I'm using the stateless functional component to add spinner while image is loading from the external resource, like so:

function ExternalImage(props) {
  const [loaded, setLoaded] = useState(false);
  function onLoad() {
    console.log('loaded');
    setLoaded(true);
  }
  return loaded
     ? <img 
        onLoad={onLoad}
        src={props.src}
        alt={props.alt}
        {...props} 
       /> 
     : <Spin />
}

And use it like so:

<ExternalImage src={image.src} alt={image.alt} className="image" />

Why would the onLoad never get called?

like image 972
mcmxc Avatar asked Jul 23 '19 11:07

mcmxc


1 Answers

When image is not loaded you aren't actually rendering the image. You need to render it for its onLoad to fire

function ExternalImage(props) {
  const [loaded, setLoaded] = useState(false);
  function onLoad() {
    console.log('loaded');
    setLoaded(true);
  }
  return (
    <>
        <img 
        style={{display: loaded? 'block': 'none'}}
        onLoad={onLoad}
        src={props.src}
        alt={props.alt}
        {...props} 
       /> 
       {!loaded && <Spin /> }
    </>
  )
}
like image 98
Shubham Khatri Avatar answered Oct 22 '22 05:10

Shubham Khatri