1

For context, <NavTreeItem> is a material-ui <TreeItem> and <OpenDialogButton> is a material-ui <Button>.

I have a component like this (simplified):

function pushLink() {
  // ...
}

function openDialog(event) {
  event.stopPropagation();
  // ...
}

<NavTreeItem onClick={pushLink}>
  <OpenDialogButton onClick={openDialog} />
  ...
  {dialogIsOpen && <Dialog />}
</NavTreeItem>

Let's say neither openDialog() nor pushLink() has been executed yet. If I click <OpenDialogButton> to open the dialog, it runs openDialog() which executes event.stopPropagation() so that the event doesn't bubble up to the tree item and executes pushLink() - just as expected. When <Dialog> is committed to the DOM, it is not nested within the <NavTreeItem> - just as expected. So far, only openDialog() has been executed.

But when I click on the <Dialog> element (or its backdrop), it executes pushLink() - undesirable behavior. It almost seems as if the click event is bubbling up to the <NavTreeItem> element - even though the <Dialog> element is not nested within it in the DOM. Why is this happening? How do I make it so that this doesn't occur?

10 Rep
  • 2,217
  • 7
  • 19
  • 33
  • My only guess is that this is React-specific behavior which propagates events if an element is nested within another _within JSX_, even if they aren't nested in the DOM. –  Jan 07 '21 at 16:50
  • If that's the case, then a simple solution would be to move `` out of ``, but this isn't ideal for my situation. –  Jan 07 '21 at 17:01
  • check https://stackoverflow.com/questions/38619981/react-prevent-event-bubbling-in-nested-components-on-click – James Jan 07 '21 at 17:02
  • BTW if you figured it out, then please add the solution as an answer. Thanks! – 10 Rep Jan 07 '21 at 17:15

1 Answers1

0

Here's the solution I found:

<NavTreeItem onClick={pushLink}>
  <OpenDialogButton onClick={openDialog} />
  ...
  <div onClick={(event) => event.stopPropagation()}>
    {dialogIsOpen && <Dialog />}
  </div>
</NavTreeItem>