S
S
Sergey Shevchenko2018-06-28 19:14:48
JavaScript
Sergey Shevchenko, 2018-06-28 19:14:48

React how do you force when you click on a child element not to process the onClick of the parent?

Hello everyone, (I think) the question is banal. There is a Parent block with a book display. Inside there is a checkbox (to add a product to comparison) when clicked, the product card should change color (the product card is a parent block). The product roll (inside) also has an image and a block with likes.
Actually the question itself: How to make sure that when you click on the likes, the product card is not highlighted for adding to the comparison?
Or more simply: How did the onClick of the parent element not work when clicking on a child element?
Link to Codepen: https ://codepen.io/Lancer-Serega/pen/bKQapr?editor...

5b35094a34f19104007248.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
glem1337, 2018-06-28
@lancer_serega

When one of the DOM nodes is clicked, the click event "bubbles" up the tree until it reaches the root or is explicitly cancelled.
React passes a "synthetic" event object to the event handler, which, among other things, has a stopPropagate method. This method (like its native counterpart) stops the event from bubbling further up the DOM tree. Here's how you can use this method in practice:

var Block = React.createClass({
    handleClose: function(e) {
        e.stopPropagation();
        alert('close');
    },
    handleClick: function(e) {
        alert('click');
    },
    render: function() {
        return (
            <div onClick={this.handleClick}>
                <span>Foo Bar Baz</span>
                <span onClick={this.handleClose}> &#215;</span>
            </div>
        );
    }
});

Simply put, you need to apply e.stopPropagation();when clicking on the element you need (like)
Link to the question on stackoverflow: https://ru.stackoverflow.com/questions/537267/reac...

I
Ilya, 2018-06-28
@ilyapashkov02

Disable popup

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question