I'm trying to use event.stopPropagation() within a ReactJS component to stop a click event from bubbling up and triggering a click event that was attached with JQuery in legacy code, but it seems like React's stopPropagation() only stops propagation to events also attached in React, and JQuery's stopPropagation() doesn't stop propagation to events attached with React.
Is there any way to make stopPropagation() work across these events? I wrote a simple JSFiddle to demonstrate these behaviors:
/** @jsx React.DOM */
var Propagation = React.createClass({
alert: function(){
alert('React Alert');
},
stopPropagation: function(e){
e.stopPropagation();
},
render: function(){
return (
<div>
<div onClick={this.alert}>
<a href="#" onClick={this.stopPropagation}>React Stop Propagation on React Event</a>
</div>
<div className="alert">
<a href="#" onClick={this.stopPropagation}>React Stop Propagation on JQuery Event</a>
</div>
<div onClick={this.alert}>
<a href="#" className="stop-propagation">JQuery Stop Propagation on React Event</a>
</div>
<div className="alert">
<a href="#" className="stop-propagation">JQuery Stop Propagation on JQuery Event</a>
</div>
</div>
);
}
});
React.renderComponent(<Propagation />, document.body);
$(function(){
$(document).on('click', '.alert', function(e){
alert('Jquery Alert');
});
$(document).on('click', '.stop-propagation', function(e){
e.stopPropagation();
});
});
event.nativeEvent.stopImmediatePropagation
to prevent other event listeners from firing, but order of execution is not guaranteed.stopImmediatePropagation
claims event listeners will be called in the order in which they were bound. If your React JS is initialized before your jQuery (as it is in your fiddle), stopping immediate propagation will work.componentDidMount
, but it might interfere with other React event handlers in unexpected ways..stop-propagation
necessarily will not work. Your example uses event delegation but is trying to stop propagation at the element. The listener needs to be bound to the element itself:$('.stop-propagation').on('click', function(e) { e.stopPropagation(); });
. This fiddle prevents all propagation like you were trying: jsfiddle.net/7LEDT/6