0

I am using onMouseDown and onMouseUp for better control. I already have onContextMenu but how I can prevent the right button click on onMouseDown and onMouseUp.I only want the left button to be clicked.

because currently 2 events triggering at the same time. My context menu and other function open at the same time.

sanket kheni
  • 1,482
  • 2
  • 12
  • 29
  • I don't believe you can prevent the event entirely, however you can detect which button is pressed and run/not run where appropriate: [How can I detect a rightmouse button event on mousedown?](https://stackoverflow.com/questions/9521519/how-can-i-detect-a-rightmouse-button-event-on-mousedown) – DBS May 10 '21 at 16:17

2 Answers2

2
onMouseDown={(event) => {
 if (event.button === 0) { ***write some code***}
}}

event.button === 0 left, event.button === 1 middle, event.button === 2 right,

sanket kheni
  • 1,482
  • 2
  • 12
  • 29
2

You can check if e.button === 2 or not. When you right click then the value of e.button is 2.

Though i'm not sure about it's browser support.

You can check this example.

const {useState} = React;

const App = () => {
  const [value, setValue] = useState('left or right click');

  const handleMouseDown = (e) => {
    if(e.button === 2) return;
    console.log('handleMouseDown');
  }
  
  const handleMouseUp = (e) => {
    if(e.button === 2) return;
    console.log('handleMouseUp');
  }
  
  const handleContextMenu = (e) => {
    console.log('handleContextMenu');
  }

  return (
    <div className="test" onMouseDown={handleMouseDown} onMouseUp={handleMouseUp} onContextMenu={handleContextMenu} >{value}</div>
  );
};

// Render it
ReactDOM.render(
  <App/>,
  document.getElementById("react")
);
.test {
  width: 100vw;
  height: 100vh;
  text-align: center;
  font-size: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Sifat Haque
  • 5,357
  • 1
  • 16
  • 23