Capture Right Click in React


Here's how to capture right click in React.

Event Handler

To capture a click, you use an onClick. That's for a left click.

If you're living on the edge and want to capture a right click, use onContextMenu. It does the same thing, but for the right mouse button.

function MyComponent() {
  function handleRightClick(evt: React.MouseEvent<HTMLButtonElement>) {
    console.log('Right click!')
  }

  return <button onContextMenu={handleRightClick}>Right Click Me</button>
}

Button Number

You do have another option. It might work well if you have a single event handler for both right and left clicks.

You can grab the mouse event and check which button was clicked:

function MyComponent() {
  function handleClick(evt: React.MouseEvent<HTMLButtonElement>) {
    if (evt.button === 2) {
      console.log('Right click!')
    } else {
      console.log('Left click!')
    }
  }

  return <button onContextMenu={handleClick}>Right Click Me</button>
}

Now, choose the right!