Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call stopPropagation in reactjs?

Tags:

reactjs

I want to stop the click event from bubling up. Therefore I added e.stopPropagation() in my code. I always get a mistake in the console, that says: Uncaught TypeError: e.stopPropagation is not a function

What is the right way to set the stopPropagation in reactjs?

      handleClick: function(index, e) {         e.stopPropagation();          ...      },  
like image 265
vuvu Avatar asked Mar 10 '16 11:03

vuvu


People also ask

How do you use stopPropagation in React?

event.stopPropagation() This will stop any parent component's event from firing. To use this: Make sure to pass the event object as a parameter. Use the stopPropagation method on the event object above your code within your event handler function.

How do you do event stopPropagation?

stopPropagation() Event Method The stopPropagation() method prevents propagation of the same event from being called. Propagation means bubbling up to parent elements or capturing down to child elements.

What is the difference between event stopPropagation and event stopImmediatePropagation?

In short: event. stopPropagation() allows other handlers on the same element to be executed, while event. stopImmediatePropagation() prevents every event from running.

What is event bubbling in react JS?

Event bubbling in React refers to when the innermost component handles an event, and events bubble outwards. In React, the innermost element will first be able to handle the event, and then surrounding elements will then be able to handle it themselves.


1 Answers

The right way is to use .stopPropagation,

var Component = React.createClass({   handleParentClick: function() {     console.log('handleParentClick');   },    handleChildClick: function(e) {     e.stopPropagation();      console.log('handleChildClick');   },    render: function() {     return <div onClick={this.handleParentClick}>       <p onClick={this.handleChildClick}>Child</p>     </div>;   } }); 

Example

Your event handlers will be passed instances of SyntheticEvent, a cross-browser wrapper around the browser's native event. It has the same interface as the browser's native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers. Event System

like image 168
Oleksandr T. Avatar answered Sep 27 '22 21:09

Oleksandr T.