Skip to content

useContextMenu

Handle the user right clicks on a target element with this hook.

Parameters

  • the ref object of the target element (default is window).

Return Values

NameTypeDescription
refRefObjectthe target element reference.
clientXNumberthe x position of the mouse.
clientYNumberthe y position of the mouse.
canShowBooleandetermins whether you should show or hide the menu.
toggleFunctiontoggle between show and hide. you can force it using a boolean as the parameter like toggle(true).

TIP

If you want to cancel the context menu, just use stopPropagation method of the mouse event:

ts
const handleRightClick = (event) => {
  event.stopPropagation();
  ...
}
const handleRightClick = (event) => {
  event.stopPropagation();
  ...
}

Example Usage

tsx
import { useContextMenu } from 'react-pre-hooks';

export default function Example() {
  const { ref, canShow, clientX, clientY } = useContextMenu();

  return (
    <div ref={ref}>
      {canShow && (
        <ul style={{ left: clientX, top: clientY }}>
          <li>Item 1.</li>
          <li>Item 2.</li>
          <li>Item 3.</li>
        </ul>
      )}
      <p>right click anywhere!</p>
    </div>
  );
}
import { useContextMenu } from 'react-pre-hooks';

export default function Example() {
  const { ref, canShow, clientX, clientY } = useContextMenu();

  return (
    <div ref={ref}>
      {canShow && (
        <ul style={{ left: clientX, top: clientY }}>
          <li>Item 1.</li>
          <li>Item 2.</li>
          <li>Item 3.</li>
        </ul>
      )}
      <p>right click anywhere!</p>
    </div>
  );
}

Released under the MIT License.