Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add GridContextMenu, which has access to Grid item menu was opened on #246

Open
TatuLund opened this issue May 10, 2024 · 0 comments
Open
Labels
enhancement New feature or request

Comments

@TatuLund
Copy link

We are lacking GridConextMenu. Hence doing ContextMenu to operate Grid items is having bad DX.

Here are some additional code you need for getting the Grid item and use it when menu item selected
First import the types you need

import { Grid, type GridElement } from '@hilla/react-components/Grid.js';
import { ContextMenu, ContextMenuItemSelectedEvent } from '@hilla/react-components/ContextMenu.js';

We need to use ref to get underlying element for listening context menu open in Grid

const gridRef = useRef<GridElement>(null);
const [contextItem, setContextItem] = useState<Item | undefined>(undefined);

We set the opening listener in useEffect using the ref. There we can get the item on which the menu was opened, can set state variable of the last item where opening happened

useEffect(() => {
  const grid = gridRef.current;
  if (grid) {
    // Workaround: Prevent opening context menu on header row.
    // @ts-expect-error vaadin-contextmenu isn't a GridElement event.
    grid.addEventListener('vaadin-contextmenu', (e) => {
      if (grid.getEventContext(e).section !== 'body') {
        e.stopPropagation();
      } else {
        const item = grid.getEventContext(e).item;
        setContextItem(item);
      }
    });
  }
}, []);

Add menu item selected listener

<ContextMenu onItemSelected={onContextMenu} items={menuItems}>

This event is triggered when user selects menu item, thus happening after open event. And we can use the state variable contextItem we set at opening

function onContextMenu(e: ContextMenuItemSelectedEvent) {
   Notification.show(contextItem?.name + ' clicked');
}
@yuriy-fix yuriy-fix added the enhancement New feature or request label May 16, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants