Search code examples
javascriptreactjsmaterial-uimouseevent

Right click on nested component triggering twice react


I am using material ui's tree component which is a bunch of nested treeItem components. I would like to have a rightClick event trigger on each individual tree node. I use onContextMenu to do so, however, since my components are nested, when I right click an inner component the right click event triggers twice, once for the inner component I just right clicked and once for its parent component. Any ideas how I can stop this from occuring?

my code:

function Tree( props ) {

  // Recursively generate tree items passed to component
  const renderTree = ( nodes ) => (
    <TreeItem key = {nodes.id} nodeId = {nodes.id} label = {nodes.name} onContextMenu = {rightClick}>
      {Array.isArray( nodes.children ) ? nodes.children.map( (node) => renderTree(node) ) : null}
    </TreeItem>
  )

  const rightClick = (event) => {
    event.preventDefault();
    alert("LOL")
  }

  return (
    <div>
    <TreeView
      defaultCollapseIcon = {<ExpandMoreIcon />}
      defaultExpandIcon = {<ChevronRightIcon />}
      multiSelect>
      {renderTree( props.treeItems )}
    </TreeView>
    </div>
  );
}

Solution

  • You can also stop the event bubbling up the DOM by stopping its propagation.

    The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. It does not, however, prevent any default behaviors from occurring; for instance, clicks on links are still processed. If you want to stop those behaviors, see the preventDefault() method.

    const rightClick = (event) => {
      event.preventDefault();
      event.stopPropagation()
      alert("LOL")
    }