React AG Data Grid - Column Menu on right Click

Viewed 23

By default the column menu of a ag grid table appears when you click on the menu icon in the column header, however the icon of this column menu is very large. Is there a way that the column menu appears on right click (similiar to the context menu in the cells)?

I had a look at the documentation, however i was not able to achieve this. https://www.ag-grid.com/archive/26.0.0/javascript-data-grid/column-menu/#customising-the-general-menu-tab

I assume it has to something with the postProcessPopup settings...

1 Answers

I made an example in V28, so you might have to check APIs for v26, but the principle should be the same.

Also, it is a bit hacky and might break in the future. The better option would be to make a header component.

Please note I added onContextMenu event with a listener on the grid container with the theme name.

  return (
    <div style={containerStyle}>
      <div
        style={containerStyle}
        className="ag-theme-alpine"
        onContextMenu={(e) => {
          openColumnMenuOnRightClick(e, gridRef);
        }}
      >
        <AgGridReact
          ref={gridRef}
          rowData={rowData}
          columnDefs={columnDefs}
          animateRows={true}
          onGridReady={onGridReady}
        ></AgGridReact>
      </div>
    </div>
  );

Below is the function where the magic happens:

  const openColumnMenuOnRightClick = (event, gridRef) => {
    const { target } = event;
    if (
      target.className.includes('header') ||
      target.parentElement.className.includes('header')
    ) {
      event.preventDefault();

      const { api } = gridRef.current;
      const colId = target.innerText.toLowerCase();
      
      api.showColumnMenuAfterMouseClick(colId, event);
    }
  };

Here is the working example in plunker: https://plnkr.co/edit/Rg2ML5XpzkkdUl1i

Related