Image onLoad event in isomorphic/universal react - register event after image is loaded Image onLoad event in isomorphic/universal react - register event after image is loaded reactjs reactjs

Image onLoad event in isomorphic/universal react - register event after image is loaded


You could check the complete property on the image before applying the onload event.

if (!img.complete) {    // add onload listener here}


Another way is to use ref and cover those both scenarios:

<img  ref={(input) => {    // onLoad replacement for SSR    if (!input) { return; }    const img = input;    const updateFunc = () => {      this.setState({ loaded: true });    };    img.onload = updateFunc;    if (img.complete) {      updateFunc();    }  }}  src={imgSrc}  alt={imgAlt}/>


This is all a bit tidier with Hooks:

const useImageLoaded = () => {  const [loaded, setLoaded] = useState(false)  const ref = useRef()  const onLoad = () => {    setLoaded(true)  }  useEffect(() => {    if (ref.current && ref.current.complete) {      onLoad()    }  })  return [ref, loaded, onLoad]}const SomeComponent = ({ src }) => {  const [ref, loaded, onLoad] = useImageLoaded()  return (    <div>      <img ref={ref} onLoad={onLoad} src={src} alt="" />      {loaded && <h1>Loaded!</h1>}    </div>  )}