useContextMenu
A hook that helps you build custom right-click context menus with mouse positioning.
✅ Features
- Tracks mouse position
- Easy integration
- Fully typed
📦 Usage
1const { position, visible, handleContextMenu } = useContextMenu() 2 3return ( 4 <div onContextMenu={handleContextMenu}> 5 Right-click me 6 {visible && ( 7 <CustomMenu x={position.x} y={position.y} /> 8 )} 9 </div> 10)
📋 Source Code
This is the full implementation of useContextMenu
1import { useRef, useState } from 'react'
2
3export function useContextMenu() {
4 const [position, setPosition] = useState<{ x: number; y: number } | null>(null)
5 const ref = useRef<HTMLDivElement | null>(null)
6
7 const open = (e: React.MouseEvent) => {
8 e.preventDefault()
9 setPosition({ x: e.pageX, y: e.pageY })
10 }
11
12 const close = () => setPosition(null)
13
14 return {
15 position,
16 open,
17 close,
18 bind: {
19 onContextMenu: open,
20 },
21 ref,
22 }
23}
24