0

I'm trying to detect left and right mouse clicks. I have a div with an onClick handler attached to it. This is what it looks like:

<div className={styles.itemSlot} onClick={this.onClick}></div>

And this is what the 'onClick' looks like:

  private readonly onClick = (evt: React.MouseEvent<HTMLImageElement>) => {
    if (evt.button === 1) {
      console.log('Left Click')
    }
    if (evt.button === 2) {
      console.log('Right Click')
    }
  };

The left click gets detected, but when I click the right button on the mouse, nothing happens. The same is true for the wheel or middle button. Only the left click gets detected.

How can I fix this issue?

Mustafa Yusuf
  • 132
  • 2
  • 13
  • 1
    Does this answer your question? [Is right click a Javascript event?](https://stackoverflow.com/questions/2405771/is-right-click-a-javascript-event) – tomerpacific Mar 28 '22 at 08:45
  • The [contextmenu](https://developer.mozilla.org/en-US/docs/Web/API/Element/contextmenu_event) event may help you with your functionality –  Mar 28 '22 at 08:47
  • @tomerpacific and @MikeS. Unfortunately no. I've seen that answer and I don't want to use `oncontextmenu`. – Mustafa Yusuf Mar 28 '22 at 09:08
  • Have you tried to use `evt.nativeEvent.button`? Also could you provide a `console.log(evt.button, evt.nativeEvent.button)` both when you are left-clicking and right-clicking? – DDomen Mar 28 '22 at 11:12
  • You could use `onmousedown` (https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent) and check the MouseEvent.button. But in the end it may just be the same as `oncontextmenu`. What do you mean with you 'don't want to use' it? – Harald Mar 30 '22 at 18:04

0 Answers0