Examples › Imperative hiding

A visible context menu hides automatically when the user clicks anywhere on the page, hits the Escape key, scrolls the or resizes the browser window.

However, you can also hide the context menu imperatively by calling the hideContextMenu function returned by the useContextMenu hook.

The useContextMenu hook also returns an isContextMenuVisible boolean that you can use to determine whether the context menu is currently visible.

In the example below, we’ll hide the context menu automatically when the user presses the H key, his mouse cursor leaves the page, or after five seconds have elapsed:

import { useHotkeys, usePageLeave, useTimeout } from '@mantine/hooks';
import { useContextMenu } from 'mantine-contextmenu';
import { useEffect } from 'react';
import { Picture } from '~/components/Picture';
import { copyImageToClipboard, downloadImage, unsplashImages } from '~/lib/images';

export function ImperativeHidingExample() {
  const { showContextMenu, hideContextMenu, isContextMenuVisible } = useContextMenu();

  // 👇 hide the context menu after five seconds have elapsed
  const { start: startHiding, clear: cancelHiding } = useTimeout(hideContextMenu, 5000);
  useEffect(() => {
    if (isContextMenuVisible) {
      startHiding();
    } else {
      cancelHiding();
    }
  }, [cancelHiding, isContextMenuVisible, startHiding]);

  // 👇 hide the context menu when the user hits the `H` key
  useHotkeys([['H', hideContextMenu]]);

  // 👇 hide the context menu when the mouse cursor leaves the page
  usePageLeave(hideContextMenu);

  // ...
  return (
    <Picture
      image={image}
      onContextMenu={showContextMenu([
        {
          key: 'copy',
          onClick: () => copyImageToClipboard(src),
        },
        {
          key: 'download',
          onClick: () => downloadImage(src),
        },
      ])}
    />
  );
}

Right-click on the image below to show the context menu:

Picture by Michael Sum | Mantine ContextMenu

Picture by Michael Sum