mantine-contextmenu: React right-click menu tutorial & examples

mantine-contextmenu: React right-click menu tutorial & examples





mantine-contextmenu: React right-click menu tutorial & examples




mantine-contextmenu: React right-click menu tutorial & examples

In short: mantine-contextmenu is a lightweight React add-on that plugs into Mantine to create accessible, themeable right-click/contextual menus. This guide covers installation, a minimal example, submenus, customization, hooks, and production-ready accessibility and keyboard handling — all without fluff.

Why mantine-contextmenu and what to expect

If you already use Mantine for UI components, mantine-contextmenu feels like a natural extension: it integrates with the Mantine theme system, exposes hooks/components, and focuses on right-click behavior and contextual actions. Expect small bundle impact, keyboard navigation, and support for nested menus (submenus).

User intent for searches like “mantine-contextmenu”, “React context menu” or “React right-click menu” is usually informational-to-technical: developers need quick setup steps, working examples, and customization options — not vendor marketing. This article targets that intent with concrete code and tips for real projects.

You’ll see the essentials here: installation, a minimal working example, advanced patterns (submenus, customizing look & feel), hooks for programmatic control, and accessibility best practices. Links to authoritative docs and example posts are included for deeper dives.

Installation and initial setup

Start by installing the package and Mantine core (if not already present). Typical commands:

npm install mantine-contextmenu @mantine/core @mantine/hooks
# or
yarn add mantine-contextmenu @mantine/core @mantine/hooks

After installing, wrap your app with MantineProvider and the ContextMenu provider if the library provides one (some integrations use a provider/hook pattern). Example imports look like:

import { MantineProvider } from '@mantine/core';
import { ContextMenuProvider } from 'mantine-contextmenu';

Then mount providers near the root so menus can position and inherit theme variables. If you prefer a lib-specific quickstart, follow the official docs: React Mantine context menu, or check the npm page for installation tips: mantine-contextmenu installation.

Minimal example — right-click menu in 5 lines

Here’s a compact example that demonstrates the essence: show a menu on right-click, choose an action, and close the menu. Replace component names if the library exposes different ones.

import { ContextMenu, MenuItem } from 'mantine-contextmenu';

function FileRow({ file }) {
  return (
    <ContextMenu
      items={[
        { label: 'Open', onClick: () => open(file) },
        { label: 'Rename', onClick: () => rename(file) },
        { label: 'Delete', onClick: () => deleteFile(file) },
      ]}
    >
      <div>{file.name}</div>
    </ContextMenu>
  );
}

Key points: the ContextMenu wraps any target element (or attaches to coordinates with a hook), accepts an items array (or children for full control), and exposes callbacks for item clicks. This pattern keeps markup declarative and easy to reason about.

For programmatic control (open/close at coordinates), use the hook variant (see next section). That approach is helpful when the menu should appear on drag-end, long-press, or when complex positioning is required.

Submenus, nested items and advanced behaviors

Submenus (nested menus) are a common requirement: think “Export → PDF/CSV” or “More actions → Move/Copy”. mantine-contextmenu typically supports nested items either via a nested items property or explicit Menu components. The implementation must handle focus management and positioning to avoid clipping and ensure keyboard navigation between parent and child menus.

When building submenus, prefer the library’s built-in nested API instead of DIY nested popovers. Built-in methods will usually manage aria attributes like aria-haspopup, aria-expanded, and focus traps that make keyboard navigation predictable for users who rely on Tab/Arrow keys.

Tip: test submenus on different viewport sizes. If your submenu would overflow the viewport, ensure the component supports flipping logic (position inversion) or implement a portal target that allows it to render in a parent container with sufficient space.

Hooks and programmatic control

To appear at cursor coordinates or to open the menu from non-wrapped elements (e.g., canvas or file list), use the library’s hooks. A common hook signature is useContextMenu() that returns an openAt(x, y, items) function and state.

const { openAt } = useContextMenu();

function onContextMenu(e) {
  e.preventDefault();
  openAt(e.clientX, e.clientY, [
    { label: 'Copy', onClick: copyFn },
    { label: 'Paste', onClick: pasteFn },
  ]);
}

Programmatic control simplifies long-press on mobile or context triggers from keyboard shortcuts. When using hooks, ensure you forward refs where needed so the context menu can measure boundaries and compute correct positions.

Also, expose close() in your hook if your workflow requires dismissing menus from external events (e.g., route change or modal open). Graceful cleanup avoids orphaned overlays that block interaction.

Customization, theming and styling

mantine-contextmenu integrates with Mantine’s theming system. You can customize colors, font sizes, spacing and provide classNames or styles props for fine-grained control. Use the theme overrides for consistent look across your app.

For per-menu customization, style props or render props let you replace the default item renderer. When you replace renderers, preserve keyboard behaviors and aria attributes — appearance should be separate from interaction logic.

Small styling checklist for production:

  • Ensure adequate hit area and contrast for menu items.
  • Preserve keyboard focus outlines and manage focus on open.
  • Handle disabled items and separators semantically (aria-disabled, role=”separator”).

Accessibility and best practices

Context menus must be accessible: support keyboard activation (Shift+F10 or ContextMenu key), arrow-key navigation, Escape to close, and screen reader-friendly roles/labels. Libraries like mantine-contextmenu often provide those behaviors out of the box, but always validate with manual tests and automated tools.

Test scenarios to include in your QA flow: open/close via keyboard, focus order when menus open, behavior on route changes, and screen-reader announcements for open state. Remember mobile: long-press or custom gestures are needed because there is no right-click.

Finally, perform a performance check: many context menus render on demand. Avoid rendering large subtrees inside menus; prefer lazy rendering for heavy content and reuse stable components wherever possible.

Where to read more (backlinks)

Official Mantine docs and examples are the authoritative source for theming and integration: React Mantine context menu. The npm package page shows the latest install instructions: mantine-contextmenu installation.

For a practical walkthrough and advanced tricks (submenus, keyboard handling), check this hands-on article: Advanced Context Menus with mantine-contextmenu on dev.to. Also inspect the project’s repo/issue tracker on GitHub for real-world issues and PRs: mantine context menu (repo).

Linking to these authoritative pages helps both developers seeking details and search engines understanding relevance for queries like “mantine-contextmenu example” and “React context menu hooks”.

FAQ

How do I install mantine-contextmenu in a React project?

Install the package and Mantine core: npm install mantine-contextmenu @mantine/core @mantine/hooks (or use yarn). Wrap your app with MantineProvider and the context menu provider/hook as described in the library docs, then import the ContextMenu components or hooks where needed.

Can mantine-contextmenu handle nested submenus?

Yes. The library supports nested menu items/submenus. Use its nested items API or nested Menu components so the library manages focus and positioning between parent and child menus. Test flipping and viewport overflow behavior to ensure usability.

How can I customize styles and integrate mantine-contextmenu with my app theme?

Customize via Mantine’s theme overrides, component-level style/className props, or render props for items. Preserve interaction semantics (keyboard, ARIA) while customizing look. Consult Mantine theming docs for tokens you can reuse.

Semantic core (keyword clusters)

Below is an expanded semantic core derived from primary inputs and common search intents. Use these keywords naturally in headings and content.

Main keywords (primary):

  • mantine-contextmenu
  • React context menu
  • React right-click menu
  • mantine-contextmenu tutorial
  • mantine-contextmenu example

Supporting / intent keywords (medium-high frequency):

  • mantine-contextmenu installation
  • React Mantine context menu
  • React contextual menu
  • React menu library
  • mantine-contextmenu setup

LSI, synonyms, and related phrases:

  • right click context menu React
  • custom context menu React
  • context menu hooks
  • nested context menus / submenus
  • context menu accessibility
  • context menu theming Mantine

Clusters (for on-page usage):

  1. Core: mantine-contextmenu, React context menu, React right-click menu, mantine-contextmenu example
  2. Install & Setup: mantine-contextmenu installation, setup, npm, yarn, MantineProvider
  3. Usage & Hooks: context menu hooks, openAt, programmatic, contextual menu
  4. Advanced: submenus, nested menus, customization, theming, accessibility

Primary targets: mantine-contextmenu, React context menu, React right-click menu

Article last updated: 2026-03-09. For code and project issues, check the library repo or the article linked above.


Share:

Leave your comments