Sometimes, we want to distinguish left and right click events in React.
In this article, we’ll look at how to distinguish left and right click events in React.
Distinguish Left and Right Click Events in React
To distinguish left and right click events in React, we can set the onClick
prop and onContextMenu
to handle left click and right click events respectively.
For instance, we write:
import React from "react";
export default function App() {
const handleClick = (e) => {
if (e.type === "click") {
console.log("Left click");
} else if (e.type === "contextmenu") {
console.log("Right click");
}
};
return (
<p onClick={handleClick} onContextMenu={handleClick}>
click me
</p>
);
}
to add the handleClick
function to handle both left and right click events.
We check which type of click it is with the e.type
propety.
If e.type
is 'click'
, then we left clicked on the p element.
And if it’s 'contextmenu'
, we did a right click.
We can also use the e.nativeEvent.which
property to do the same check.
To do this, we write:
import React from "react";
export default function App() {
const handleClick = (e) => {
if (e.nativeEvent.which === 1) {
console.log("Left click");
} else if (e.nativeEvent.which === 3) {
console.log("Right click");
}
};
return (
<p onClick={handleClick} onContextMenu={handleClick}>
click me
</p>
);
}
If e.nativeEvent.which
is 1, then we did a left click.
And if it’s 3, then we did a right click.
Conclusion
To distinguish left and right click events in React, we can set the onClick
prop and onContextMenu
to handle left click and right click events respectively.