React: e.stopPropagation() seems to not be working as expect.

Created on 10 Jul 2015  路  9Comments  路  Source: facebook/react

I found this issue when I attempted to integrate ReacJs and a jQuery widget.

I bind an click event on input element and document like follow:

var Search = React.createClass({
    handleClick: function(e) {
        e.stopPropagation();
    },
    render: function() {
        return <input onClick={this.handleClick} />
    }
});
document.addEventListener('click', function() {
    console.log('propagation')
}, false);

And everytime I click the input element, chrome devtool logs 'propagation' message. Should not document element can not receive click event? I'm confused, Did I miss something?

Most helpful comment

a workaround, use window.addEventListener() to replace document.addEventListener, event.stopPropagation() can stop event propagate to window.

All 9 comments

React (currently) uses a listener on the document for (almost) all events, so by the time your component receives the event it has already bubbled all the way up to the document and stopping it only stops it from synthetically bubbling up through the React hierarchy.

Related #2050

got it, many thanks :)

You can reproduce this issue in the following jsbin:

http://jsbin.com/rafitiq/edit?html,js,output

a workaround, use window.addEventListener() to replace document.addEventListener, event.stopPropagation() can stop event propagate to window.

@baurine You saved my life!

The change to "window" did not help me, at least when click happened outside of the initial component

We're fixing this in React 17.

@gaearon I'm not sure that I got it correctly, but why a case when a user attaches an event listener to a specific DOM node (not to document) isn't working? I've created a fast example here to demonstrate my case.

Was this page helpful?
0 / 5 - 0 ratings