Switch theme

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 destructuring the result returned by the useContextMenu hook into:
  • showContextMenu → a function that can be used to show the context menu;
  • hideContextMenu → a function that can be used to hide the context menu;
  • isContextMenuVisible → a boolean representing whether the context menu is currently visible or not.
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/image';
export default 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
MIT LicenseSponsor the author
Built by Ionut-Cristian Florescu, the author of Mantine DataTable.
Please sponsor my work if you find it useful.
GitHub StarsNPM Downloads