July 20, 2015

Caveats regarding react event delegation

React's mechanism of vitual DOM is well known. I recently came into two caveats that might need some attention for js developers.

Event delegation

React's event delegation handler is attached to the document. When it receives an event, it dispatch a synthetic event accross the virtual DOM.
That mean the following log is gonna be unusual.

var HelloMessage = React.createClass({
    componentDidMount() {
        document.addEventListener('click', function () {
            console.log('doc click');
        });
        document.body.addEventListener('click', function () {
            console.log('body click');
        });
    },
    onClick: function() {
        console.log('div click');
    },
    render: function() {
        return <div ref="div" onClick={this.onClick}>Hello</div>;
    }
});

React.render(<HelloMessage/>, document.getElementById('root'));

The log is incredibly body > div > doc.

Actually, stop all event propagating through the body will stop react entirely.

document.body.addEventListener('click', function (evt) {
    evt.stopPropagation();
});

http://stackoverflow.com/questions/25862475/react-and-jquery-event-handlers-fired-in-wrong-order

Event propagation

Since SyntheticEvent is independent of the DOM, and that event handler is attached to the document. stopPropagation in fade DOM will not affect the original event. By the time react's handler got an event, it should have already finished it's bubbling phase.

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket