10

I have a React Server Side rendered component with img tag. I want to attach an onload event listener on the image tag and made the component like below:

render () {
  return (
    <img onLoad={() => { console.log('Image loaded'); }} src='/abc.jpg'/>
  )
}

Ideally React's renderToString method should have generated an HTML template like below:

<img onload='function () { console.log('Image loaded'); }' src='/abc.jpg' />

but it doesn't. What am I missing? I checked there was a similar issue here but with no solution

Aditya Singh
  • 15,810
  • 15
  • 45
  • 67

1 Answers1

3

React doesn't use inline event handlers in the dom/html. The listeners are added with JavaScript when your app loads on the client.

This has the benefit that they don't depend on global variables, and that it can use event delegation for performance and other reasons.

Take this code for example:

var a = 1;
<div onClick={() => console.log(a)}</div>

There's no way React could create that as an inline event handler.

Brigand
  • 84,529
  • 20
  • 165
  • 173
  • Can you please give an example on how to this client side? I have a script that im sending server side and I cant seem to be able to make sure it loads – Lior Alon Nov 26 '20 at 09:27