Skip to content

useContextMenu

Hook to add contextmenu event listener. The contextmenu event fires when the user attempts to open a context menu. This event is typically triggered by clicking the right mouse button, or by pressing the context menu key.

Demo

INFO

The component uses useContextMenu hook and renders two paragraph. It uses the hook to disabled native contextmenu event on first paragraph.

Loading demo…
Show source code
tsx
import { useCallback, useRef } from "react"
import { useContextMenu } from "../../../..";

export const UseContextMenu = () => {
	const pRef = useRef<HTMLParagraphElement>(null);
	useContextMenu({
		element: pRef,
		listener: useCallback((evt: PointerEvent) => {
			evt.preventDefault();
		}, [])
	});

	return <div>
		<p ref={pRef}>The context menu on this paragraph is disabled.</p>
		<p>On this paragraph context menu is enabled.</p>
	</div>
}

Types

UseContextMenuProps

Parameters accepted by useContextMenu.

PropertyTypeRequiredDescription
elementRefObject<HTMLElement> \| WindowThe target on which the context menu event listener is registered. Accepts either a React RefObject&lt;HTMLElement&gt; or a direct Window reference.
listener(evt: PointerEvent) => void \| Promise<void>Callback invoked when the context menu event fires on the target element. Receives the native {@link PointerEvent} that triggered the context menu. May return a Promise for async handlers.
effectType"normal" \| "layout"Controls which React effect hook is used to register the event listener: - "normal" (default) — Uses useEffect, which runs asynchronously after the browser has painted. - "layout" — Uses useLayoutEffect, which runs synchronously after DOM mutations but before the browser paints. Prefer this when the listener needs to read or modify layout immediately.
listenerOptsboolean \| AddEventListenerOptionsOptions forwarded to addEventListener as the third argument. Accepts either a boolean shorthand for capture or a full {@link AddEventListenerOptions} object. When omitted, the listener is registered with the browser defaults.

Released under the MIT License.