Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

499
Visualizações
React Synthetic Event distinguish Left and Right click events

I am trying to distinguish between left and right clicks in an onClick function:

const App = () => {
  const handleClick = (e) => {
    // detect a left click
    if (e.which == 1){ 
      // do something
    }
  };
  return <p onClick={handleClick}>Something</p>;
};

Turns out e.which is undefined for Synthetic Events. How can I distinguish between left and right clicks here?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

In modern versions of React (v16+), both onClick and onContextMenu props need to be passed to detect both left- and right-click events:

return <p onClick={handleClick} onContextMenu={handleClick}>Something</p>

You can either check against e.nativeEvent.button (as the other answer implies), or check e.type on the synthetic event itself.

Using e.type

const handleClick = (e) => {
  if (e.type === 'click') {
    console.log('Left click');
  } else if (e.type === 'contextmenu') {
    console.log('Right click');
  }
};

Using e.nativeEvent

const handleClick = (e) => {
  if (e.nativeEvent.button === 0) {
    console.log('Left click');
  } else if (e.nativeEvent.button === 2) {
    console.log('Right click');
  }
};

Here's an updated demo demonstrating how this works.

You may also want to read the React documentation for SyntheticEvent.

(original demo)

over 4 years ago · Santiago Trujillo Relatório

0

The property you're looking for is e.button or e.buttons.

The button number that was pressed when the mouse event was fired: Left button=0, middle button=1 (if present), right button=2.
– MDN:Web/Events/click

However, with or without react, I'm only getting click events with the left mouse button (trackpad). You could use onMouseDown which works for me.

Here's a demo using e.buttons. You may want to preventDefault in onContextMenu also.

over 4 years ago · Santiago Trujillo Relatório

0

Use:

if (e.button === 0) { // or e.nativeEvent.which === 1
    // do something on left click
}

Here is a DEMO

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda