pedro.zena
pedro.zena

Reputation: 391

Material-ui: How to stop propagation of click event in nested components

I have an IconMenu component inside a Paper component. I would like to prevent the propagation of the click event on the inner component (the IconMenu). That's what I came up with, without significant results (I also tried substituting onClick with onTouchTap, onMouseUp with same effects): the _iconMenuClick method is never called.

render() {
     return (
         <Paper onClick={this._onClick}>
             <IconMenu iconButtonElement={iconButtonElement} onClick={this._iconMenuClick}>
                 {menuItems}
             </IconMenu>
         </Paper>
     );
}

_iconMenuClick(event) {
    MenuItem.onClick(event);
    event.stopPropagation();
}

Upvotes: 20

Views: 36104

Answers (3)

Rahul Makhija
Rahul Makhija

Reputation: 609

In addition to using event.stopPropagation(); It is useful to note that it should be written within a onClick event handler.

I made the mistake of writing it inside an onChange event handler, and that wasn't working.

I found that solution here

EDIT:

<ListItem button onClick={this.handleListItemClick}>
-       <Checkbox onChange={this.handleCheckboxChange} />
+       <Checkbox onClick={this.handleCheckboxChange} />
      </ListItem>

Upvotes: 20

Tretyakov Pavel
Tretyakov Pavel

Reputation: 508

For stopping top node bubble events :-) event.stopPropagation(); event.preventDefault();

Upvotes: 15

pedro.zena
pedro.zena

Reputation: 391

The workaround I suggest is the following:

render() {
     return (
         <Paper onClick={this._onClick}>
             <IconMenu iconButtonElement={iconButtonElement}>
                 {menuItems}
             </IconMenu>
             ...
         </Paper>
     );
}

_onClick(event){
    if(event.target.innerText==""){ //Or any condition that distinguish the IconMenu from the Paper element
        event.stopPropagation();
        return 0;
    }
    //continue with normal behaviour
    ...
}

Upvotes: 1

Related Questions