Home > Software design >  How to add MUI DataGrid Edit/delete Button
How to add MUI DataGrid Edit/delete Button

Time:09-27

I am having a hard time adding custom buttons per row in the DataGrid component.

This is my code:

const columns = [
    { field: 'model_id', headerName: 'ID', width: 70, sortable: false },
    { field: 'model_code', headerName: 'Model Code', width: 130 },
    { field: 'model_description', headerName: 'Description', width: 400 },
    { field: 'actions', headerName: 'Actions', width: 400 }
];

DataGrid:

<DataGrid
rows={models}
columns={columns}
getRowId={(row) => row.model_id}
pageSize={5}
rowsPerPageOptions={[5]}
checkboxSelection />

What I want per row: enter image description here

CodePudding user response:

You can use renderCell function in column definition array like this:

const onButtonClick = (e, row) => {
    e.stopPropagation();
    //do whatever you want with the row
};

const columns = [
    { field: 'model_id', headerName: 'ID', width: 70, sortable: false },
    { field: 'model_code', headerName: 'Model Code', width: 130 },
    { field: 'model_description', headerName: 'Description', width: 400 },
    { field: 'actions', headerName: 'Actions', width: 400, renderCell: (params) => {
        return (
          <Button
            onClick={(e) => onButtonClick(e, params.row)}
            variant="contained"
          >
            Delete
          </Button>
        );
      } }
];

You can take a look at this sandbox for a live working example of this solution.

  • Related