2

Using the mui-datatable library in react, create a custom column using customBodyRender to add a menu and when you click on one of the options, it will perform an action.

The problem is that when you click on the action, the data that enters the function are always those of the last record in the table, regardless of selecting the menu in the first row, the data is always the last.

What I need is that when I click on the menu of a row, it returns the data of that row.

Sample code: https://codesandbox.io/s/wonderful-mclaren-ivvlq?file=/src/App.js

enter image description here

enter image description here

Cena
  • 3,316
  • 2
  • 17
  • 34

1 Answers1

1

I've also experienced this. The way I solved it is to set the row selected index in a state variable when selecting the Menu icon, and not inside MenuItem. The Index is passed on from customBodyRenderLite or customBodyRender.

  const [anchorIndex, setAnchorIndex] = useState(0);

  const handleClick = (event, index) => {
    setAnchorEl(event.currentTarget);
    setAnchorIndex(index);
  };

  const iconButtonElement = (index) => {
    return (
      <div>
        <IconButton
          aria-label="More"
          aria-owns={open ? "long-menu" : null}
          aria-haspopup="true"
          onClick={event => handleClick(event, index)}
        >
          <MoreVertIcon color={"action"}/>
        </IconButton>
        {rightIconMenu(index)}
      </div>
    )
  }

When something should be action on the menu item, it would use the value in the state.

  const rightIconMenu = () => {
    return (
      <Menu elevation={2} anchorEl={anchorEl} open={open} onClose={onMenuClose}>
        <MenuItem onClick={handleCellClick}>View</MenuItem>
      </Menu>
    )
  };

  function handleCellClick() {
    history.push('/vehicleForm', {data: currentDataSet[anchorIndex]});
  }
user2210411
  • 1,497
  • 1
  • 9
  • 7