2

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.

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230
Batman
  • 5,563
  • 18
  • 79
  • 155
  • prevent default should stop event bubbling – sandeep joshi Sep 19 '20 at 09:26
  • @sandeepjoshi your assumption is wrong. `stopPropagation()` will stop the event from bubbling up while `preventDefault()` will only surpress the default behavior of the event. The code provided in the question is in the right direction but it doesn't work because of a React design quirk. – NearHuscarl Sep 19 '20 at 12:18

2 Answers2

6

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

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230
0

There is also workaround with preventDefault()

Inside cell you might have code like this:

<div
  onClick={(e) => e.preventDefault()}
>
 <Button />
</div>

And use original handler:

<AgGrid 
  onRowClicked={(row) => {
    if(row.event.defaultPrevented) {
      return null
    }

    doSomethingHere()
  }}
/>
Vladislav Zaynchkovsky
  • 2,461
  • 2
  • 14
  • 22