Skip to content

Instantly share code, notes, and snippets.

@mCzolko
Last active May 10, 2021 08:58
Show Gist options
  • Save mCzolko/1812d85e18a5d005c74f1fdc49cde5ee to your computer and use it in GitHub Desktop.
Save mCzolko/1812d85e18a5d005c74f1fdc49cde5ee to your computer and use it in GitHub Desktop.
ReactJS right click (contextmenu) handler
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