Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 427
ambar Avatar asked May 10 '18 12:05

ambar


People also ask

How do I detect a click outside an element in React JS?

jQuery closest() is used to see if the target from a click event has the dom element as one of its parents. If there is a match the click event belongs to one of the children and is thus not considered to be outside of the component.

How do you trigger click in React?

To add the click event in React using plain JavaScript, you need to use addEventListener() to assign the click event to an element. Create one <button> element as ref props so that it can be accessed to trigger the click event.

Can I use onClick on Div React?

To set your mind at ease, the onClick event does work with divs in react, so double-check your code syntax.


2 Answers

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.

like image 57
Jacob Weisenburger Avatar answered Sep 17 '22 11:09

Jacob Weisenburger


The modern way of doing it is through the onAuxClick event:

import Card from 'react-bootstrap/Card';
import React, { Component } from 'react';

export class MyComponent extends Component {

  onAuxClick(event) {
    if (event.button === 1) {
      // Middle mouse button has been clicked! Do what you will with it...
    }
  }
    
  render() {
    return (
      <Card onAuxClick={this.onAuxClick.bind(this)}>
      </Card>
    );
}
like image 38
Omid Ariyan Avatar answered Sep 20 '22 11:09

Omid Ariyan