Home > Back-end >  MUI table icon button in a row where row is clickable
MUI table icon button in a row where row is clickable

Time:11-12

The table rows are clickable:

<TableRow
  sx={{ '&.MuiTableRow-root': { cursor: 'pointer' } }}
  hover
  key={row.id}
  onClick={() => handleRowClick(row.id)}
>

I have an icon button in one column:

  <TableCell>
  <Tooltip title='Survey options'>
    <IconButton
      onClick={() => console.log('button clicked!')}
    >
      <MoreHoriz />
    </IconButton>
  </Tooltip>
  </TableCell>

The problem is when clicking the icon button it also triggers the onClick of the entire row:

Clicking this:

onClick={() => console.log('button clicked!')}

Also triggers this:

 onClick={() => handleRowClick(row.id)}

Is there a way to separate the clicking behavior? I want to be able to click each one separately.

CodePudding user response:

In the IconButton onClick, modify the code like this,

 onClick={(event) => {event.stopPropagation(); console.log('button clicked!');}}

The stopPropagation() method prevents propagation of the same event from being called. Propagation means bubbling up to parent elements or capturing down to child elements.

  • Related