Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why react server side rendering strips event handlers?

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

like image 616
Aditya Singh Avatar asked Mar 29 '17 07:03

Aditya Singh


1 Answers

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.

like image 162
Brigand Avatar answered Nov 17 '22 21:11

Brigand