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)