Last active
May 10, 2021 08:58
-
-
Save mCzolko/1812d85e18a5d005c74f1fdc49cde5ee to your computer and use it in GitHub Desktop.
ReactJS right click (contextmenu) handler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createElement, useEffect, useRef } from 'react' | |
const RightClick = ({ as = 'div', onRightClick, children, ...rest }) => { | |
const ref = useRef() | |
useEffect(() => { | |
const handler = e => { | |
e.stopPropagation() | |
e.preventDefault() | |
onRightClick(e) | |
} | |
const instance = ref.current // Capturing mutation in order to have reference in "unmount", thanks to @vavdav | |
// @ts-ignore | |
instance.addEventListener('contextmenu', handler) | |
// @ts-ignore | |
return () => instance.removeEventListener('contextmenu', handler) | |
}) | |
return createElement( | |
as, | |
{ | |
...rest, | |
ref | |
}, | |
children | |
) | |
} | |
export default RightClick |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment