Skip to content

ContextMenu2 migration

Adi Dahiya edited this page Mar 18, 2021 · 9 revisions

Requirements

  • <ContextMenu2> is provided in the @blueprintjs/popover2 package, so make sure to check out the Popover2 migration guide.

Notable changes compared to ContextMenu & ContextMenuTarget

The context menu API has been simplified greatly so that it works much more like a popover. The new component does not require your build system to support decorators and it can be used with function components. It wraps a target element which will receive contextmenu events (right click) and expects menu content supplied as a prop:

import { Menu, MenuItem } from "@blueprintjs/core";
import { ContextMenu2 } from "@blueprintjs/popover2";

export default function ContextMenuExample() {
    return (
        <ContextMenu2
            content={
                <Menu>
                    <MenuItem text="Save" />
                    <MenuItem text="Save as..." />
                    <MenuItem text="Delete..." intent="danger" />
                </Menu>
            }
        >
            <div className="my-context-menu-target">
                Right click me!
            </div>
        </ContextMenu2>
    );
}

Fixed positioning containing block

The upgrade to Popover2 produced some layout challenges for ContextMenu2, which uses position: fixed on its generated target element (rendered as a sibling of whatever target is supplied as children). When a ContextMenu2 exists within a DOM subtree which has a CSS containing block offset from the document, clientX and clientY properties of a context menu mouse event are insufficient to compute the rendered position of a context menu. ContextMenu2 needs to know the offset of this containing block in order to compensate for it and render the menu correctly. Such containing blocks are present in an application when, for example, a CSS transform` property is set on an element (more info here).

Blueprint components which create containing blocks as described above are now identified with the new class "bp4-fixed-positioning-containing-block" (for example, <Table> and <Tree>). ContextMenu2 can query for this class in the DOM tree to figure out how to position itself. If you find that migrating to ContextMenu2 results in menus rendered at the wrong coordinates (offset from where you clicked), consider using this class (Classes.FIXED_POSITIONING_CONTAINING_BLOCK) in your application as well, in the relevant locations.

Clone this wiki locally