Search code examples
reactjstypescriptreact-hooksmaterial-uimui-datatable

How to delete a row when a button is clicked inside a DataGrid column?


I have a data table with users and I want to make a delete button work on the rows, but it seems that it cannot be done by reactish means.

The DataGrid is used like this:

<DataGrid
  rows={users}
  columns={columns}
  pageSize={5}
  checkboxSelection
/>

I have a column with custom renderCell function that shows some action buttons. The column definition is this:

{
  field: "actions",
  headerName: "",
  width: 120,
  type: "",
  sortable: false,
  renderCell: (
    params: GridCellParams
  ): React.ReactElement<any, string | React.JSXElementConstructor<any>> => {
    return (
      <UserRowActions
        userId={params.getValue(params.id, "id")?.toString()!}
      />
    );
  }
}

The params object offers a few properties but I do not know how to do something like this: delete the row on which a button was clicked, a button that is defined in the UserRowActions component.

I would also like to find whether it is not possible to do this using the MUI DataGrid component as it is today.

I don't know what to do since the API does not look reactish to me right now.

I use:

"@material-ui/core": "^4.12.1",
"@material-ui/data-grid": "^4.0.0-alpha.30",
"react": "^16.14.0",

Solution

  • I made a context specially for the data grid action buttons:

    export const DataGridContext = React.createContext<{ deleteUser?: (uid: string) => void }>({});
    
    // ...
    
    const { data: users, isLoading, isError } = useGetUsersQuery();
    
    const [usersRows, setUsersRows] = useState<IUser[]>([]);
    
    useEffect(() => {
      if (typeof users !== 'undefined') {
        setUsersRows(users);
      }
    }, [users]);
    
    <DataGridContext.Provider value={{ deleteUser: (uid: string) => {
      const newRows = [...usersRows];
      const idx = newRows.findIndex(u => u.id === uid);
    
      if (idx > -1) {
        newRows.splice(idx, 1);
        setUsersRows(newRows);
      }
    }}}>
      <DataGrid
        rows={usersRows} // ...
      />
    </DataGridContext.Provider>
    
    // In the UserRowActions component:
    
    const dataGrid = useContext(DataGridContext);
    
    // ...
    
    dataGrid.deleteUser!(userId);