0

I have a React component for rendering customized images. In a simplified form, it looks like this:

function MyImage(props) {
  return <img src={props.src} onLoad={props.onLoad} />
}

The webpage is server-rendered by ReactDOMServer and the <img> elements are (intentionally) already present in the initial HTML document. However, their onLoad event handlers are not. I believe that is a feature of ReactDOMServer.

What can sometimes happen is that some of the customized images, especially the smaller ones, can finish loading before JavaScript is loaded or before it starts running or at least before React sets up the onLoad event handlers. As a result, the onLoad events on these images do not cause any event handlers to be called.

Is there a way to ensure that the onLoad event handlers, which are set up within a React-rendered <img> elements, will always be called after the underlying images finish loading?

My most important constraints are that I would like to use React and the server-rendered HTML page needs to contain the <img> elements with their src attributes correctly set.

Peter Bašista
  • 749
  • 9
  • 22

1 Answers1

0

You can move your onLoad handlers to the componentDidMount() method. See docs

koolkat
  • 706
  • 3
  • 8
  • 23
  • I do not see what you mean exactly and how it may help with my particular problem. Please clarify. – Peter Bašista Sep 07 '17 at 05:59
  • I still need the `onLoad` event handler to be called when image finishes loading, so I cannot "move" the event handlers away from the `` elements. Do you mean to just call the event handler manually in `componentDidMount` (if `image.complete` is true)? – Peter Bašista Sep 07 '17 at 08:38
  • 1
    The DOM is accessible from the `componentDidMount` phase, which means your image should have finished loading. So, yes, I mean manually call the event handler inside it. – koolkat Sep 07 '17 at 18:02
  • The image does not necessarily have to finish loading by the time `componentDidMount` is called. It would just be present in the DOM. But anyway, checking for it being fully loaded at that point and eventually calling the `onLoad` handler if needed should help. Please update your answer so that it is clear what you mean. – Peter Bašista Sep 08 '17 at 07:07