Coder
Coder

Reputation: 610

How NOT to pass click event to the children in react?

I use material-ui.

In this code https://codesandbox.io/s/y4jwv4ry1

  1. I have one parent component SimplePopper which renders Toggle Button and which is wrapped inside a Popper.

  2. Root div of SimplePopper is clickable (I can't transfer this click event to Botton coz in the actual code which I am writing I am not supposed to modify the existing code)

  3. Coming to the application level:

    a. I have a Toggle button, if I click on it I get log 'parent Button'.

    b. If I hover on the Toggle button I get Popper.

  4. Since I have onClick is already on the root of the parentSimplePopper, if I click anywhere inside the Popper, it will trigger the parent click event. How to prevent triggering any event present in the Parent by clicking on the children?

Please check out the code here https://codesandbox.io/s/y4jwv4ry1

Upvotes: 0

Views: 1404

Answers (1)

Jayavel
Jayavel

Reputation: 3407

You need to do two things :

In SimplePopper component :

<div 
     onClick={this.handleClickButton} 
     ref={(node) => { this.parentNode = node }}> //added ref
            <PopperExample>
                <Button>Toggle</Button>
            </PopperExample>
</div>

and in handleClickButton :

handleClickButton = e => {
    if (this.parentNode !== null && this.parentNode !== undefined) {
        this.parentNode.contains(e.target) && console.log('parent Button');
    }
};

Function will be executed, if this.parentNode contains the correct target.

and in PopperExample :

handleButtonPopperClick = e => {
    e.preventDefault();
    e.stopPropagation();
    this.setState(state => ({
        showDiv: true
    }));
};

Working demo

Upvotes: 1

Related Questions