Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
111
rated 0 times [  116] [ 5]  / answers: 1 / hits: 63873  / 9 Years ago, mon, june 29, 2015, 12:00:00

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?


More From » reactjs

 Answers
13

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)


[#66000] Friday, June 26, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
parker

Total Points: 259
Total Questions: 109
Total Answers: 97

Location: Zambia
Member since Thu, Jun 25, 2020
4 Years ago
;