Samuel Web
Samuel Web

Reputation: 3

How to use a material-ui Menu inside a mui-datatable on event handler

I am trying to make the openFilePreviewDialog(id) action return the id of its row.

Problem: it's returning the wrong id, instead of returning id=7, its returned 8

[
  {
    name: "id",
    label: " ",
    options: {
      filter: true,
      sort: false,
      customBodyRender: id => {
        const options = ["View", "Signature", "Download", "Share", "Delete"];

        return (
          <div>
            <IconButton
              className={classes.iconButton}
              aria-label="more"
              aria-controls="long-menu"
              aria-haspopup="true"
              onClick={handleClick}
            >
              <MoreVertRounded />
            </IconButton>
            <Menu
              id="long-menu"
              anchorEl={anchorEl}
              keepMounted
              open={open}
              onClose={handleClose}
            >
              {options.map(option => (
                <MenuItem
                  key={option}
                  onClick={() => openFilePreviewDialog(id)}
                >
                  {option}
                </MenuItem>
              ))}
            </Menu>
          </div>
        );
      }
    }
  }
];

Upvotes: 0

Views: 1464

Answers (1)

Khabir
Khabir

Reputation: 5854

MUIDatatable always gets the last value in id field, it does not matter which index you clicked on. Perhaps it's a bug in MUIDatatable. But I find out an alternate solution for you. You need to handle onRowClick as below:

const options = {
    filterType: 'dropdown',
    responsive: 'scrollFullHeight',
    serverSide: true,
    count: total,
    page: page,
    searchText: tableState.options.searchText,
    onRowClick: handleRowClick
}

Then you store the Id using following code (services is the collection of data that is populated on MUIDatatable). I used UseState to store id:

const [serviceId, setServiceId] = useState(0);

const handleRowClick = (rowData, rowMeta) => {
    setServiceId(services[rowMeta.dataIndex].id);
};

Then in your function openFilePreviewDialog you can use that id:

function openFilePreviewDialog(id) {
    console.log(serviceId, 'serviceRequestId');
}

Upvotes: 1

Related Questions