Search code examples
javascripthtmlreactjsmouseevent

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


I am trying to find a way to detect middle click event in React JS but so far haven't succeeded in doing so.

In Chrome React's Synthetic Click event does show the button clicked ->

mouseClickEvent.button === 0 // Left

mouseClickEvent.button === 1 // Middle but it does not execute the code at all

mouseClickEvent.button === 2 // Right (There is also onContextMenu with event.preventDefault() )

Please share your views.


Solution

  • 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.