I want to implement context menus like this:
But I can only achieve this so far: =/src/DataGridTest.tsx
The contextmenu
event fired after clicking on a cell (or row).
But I want to immediately fire the contextmenu
event.
What should I do?
I want to implement context menus like this: https://fancygrid./samples/miscellaneous/context-menu
But I can only achieve this so far: https://codesandbox.io/s/xenodochial-snow-pz1fr?file=/src/DataGridTest.tsx
The contextmenu
event fired after clicking on a cell (or row).
But I want to immediately fire the contextmenu
event.
What should I do?
In addition to Chris Wong's answer, you can also do the following:
<DataGridPremium
rows={rows}
slotProps={{
row: {
onContextMenu: (e) => handleRowContextMenu(e),
style: { cursor: 'context-menu' },
},
}}
{...props}
/>
Then, you can get the row:
const handleRowContextMenu = (event: React.MouseEvent<HTMLDivElement>) => {
event.preventDefault();
if (!event.currentTarget) {
return;
}
const rowId = Number((event.currentTarget as HTMLDivElement).getAttribute('data-id'));
const record = rows.find((row) => row.id === rowId);
if (!record) {
return;
}
// open a context menu
setContextMenu(
contextMenu === null ? { mouseX: event.clientX, mouseY: event.clientY, record } : null
);
};
Use onContextMenu
on the parent:
const onContextMenu = (e: React.SyntheticEvent): void => {
let target = e.target as HTMLElement;
console.log(target.innerHTML);
};
...
<div style={{ height: 300, width: "100%" }} onContextMenu={onContextMenu}>
...
There is a demo.