Is there any way to detect middle click in React JS?

You can add a mouseDown event and then detect the middle button click like:

handleMouseDown = (event) => {
   if(event.button === 1) {
      // do something on middle mouse button click
   }
}

You code might look like:

class App extends React.Component {
   constructor() {
     super();

     this.onMouseDown = this.onMouseDown.bind(this);
   }
   componentDidMount() {
       document.addEventListener('mousedown', this.onMouseDown);
   }
   componentWillUnmount() {
       document.removeEventListener('mousedown', this.onMouseDown);
   }
   onMouseDown(event) {
       if (event.button === 1) {
          // do something on middle mouse button click
       }
   }
   render() {
     // ...
   }
}

You can find more information on MouseEvent.button here: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button

Be careful. Using mousedown won't always get you the behavior you want. A "click" is both a mousedown and a mouseup where the x and y values haven't changed. Ideally, your solution would store the x and y values on a mousedown and when mouseup occurs, you would measure to make sure they're in the same spot.

Even better than mousedown would be pointerdown. This configures compatibility with "touch" and "pen" events as well as "mouse" events. I highly recommend this method if pointer events are compatible with your app's compatible browsers.


If you are using a stateless component:

JS

const mouseDownHandler = ( event ) => {
  if( event.button === 1 ) {
    // do something on middle mouse button click
  }
}

JSX

<div onMouseDown={mouseDownHandler}>Click me</div>

Hope this helps.