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.
You can move your
onLoad
handlers to thecomponentDidMount()
method. See docs