javascriptreactjsag-gridag-grid-react

Ag-Grid Prevent onRowClicked event when clicking icon inside cell


I have a cell renderer that returns the name property and objects on a row:

const nameRenderer = ({ value, data }) => {
    const { id: queueId } = data;
    return (
      <Box>
        <div className="row-hidden-menu">
            <IconButton
              icon="menu"
              onClick={({ event }) => {
                event.preventDefault();
                event.stopPropagation();
                onMenuClick();
              }}
            />
        </div>
      </Box>
    );
  };

enter image description here

The issue I have is that I have an onRowClick function but I don't want that function to be called when I click the icon from the nameRenderer. Right now when the menu opens, the onRowClicked event navigates to a new page.


Solution

  • See this answer for more in-depth explanation, but the gist is that the event that you receive from the onClick callback is React's synthetic event which is a wrapper of the native event. Calling stopPropagation() from a synthetic event will not stop the real event from bubbling up and it is a quirk of the React framework for a long time.

    Solution: attach your onClick event handler to the real DOM element instead.

    function ButtonCellRenderer() {
      return (
        <button
          ref={(ref) => {
            if (!ref) return;
    
            ref.onclick = (e) => {
              console.log("native event handler");
              e.stopPropagation(); // this works
              // put your logic here instead because e.stopPropagation() will
              // stop React's synthetic event
            };
          }}
          onClick={(e) => {
            e.stopPropagation(); // this doesn't work
          }}
        >
          Click me
        </button>
      );
    }
    

    Live Demo

    Edit 63964553/ag-grid-prevent-onrowclicked-event-when-clicking-icon-inside-cell