0

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>
  );
}

1 Answer 1

1

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")
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.