I have this scenario, where when parent element is clicked, it flips to show a child element with different colours. Unfortunately, when the user clicks on one of the colours, the 'click' event on parent is also triggered.
How can I stop the event trigger on parent when the child is clicked?
Possible solutions I am wondering:
CSS?
Append pointer-events : none
class to the parent when the child is clicked. However, this would mean that the parent will need to be cleansed of the pointer-events
class later.
Using Ref?
Record the ref
of the parent React
element & upon click on the child, compare the event.target
against the ref? I don't like this because I don't like the global ref
.
Thoughts and the better solution would be much appreciated. The question is: How can I stop the event trigger on parent when the child is clicked?
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.
You can use stopPropagation
stopPropagation
- Prevents further propagation of the current event in the bubbling phase
var App = React.createClass({ handleParentClick: function (e) { console.log('parent'); }, handleChildClick: function (e) { e.stopPropagation(); console.log('child'); }, render: function() { return <div> <p onClick={this.handleParentClick}> <span onClick={this.handleChildClick}>Click</span> </p> </div>; } }); ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div>
I had the same issue in React and solved it using the solution bellow:
if(e.currentTarget != e.target ) return; .......
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With