Search code examples
reactjsmaterial-uimui-x-data-gridmui-x

How to add a button to every row in MUI X DataGrid


I can't add a button into every row of MUI X DataGrid. I have an MUI X DataGrid which I render like this:

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

I have added into the columns variable 'actions' column where the button should be rows are just a data object I get from the props. How can I add a button to every row (for editing the row)? I have tried mapping the data array but it is not possible to add a JSX button into every object of data.


Solution

  • You can add your custom component by overriding GridColDef.renderCell method and return whatever element you want.

    The example below displays an action column that renders a single button in each row. When clicking the button, it alerts the current row data in JSON string:

    const columns: GridColDef[] = [
      { field: "id", headerName: "ID", width: 70 },
      {
        field: "action",
        headerName: "Action",
        sortable: false,
        renderCell: (params) => {
          const onClick = (e) => {
            e.stopPropagation(); // don't select this row after clicking
    
            const api: GridApi = params.api;
            const thisRow: Record<string, GridCellValue> = {};
    
            api
              .getAllColumns()
              .filter((c) => c.field !== "__check__" && !!c)
              .forEach(
                (c) => (thisRow[c.field] = params.getValue(params.id, c.field))
              );
    
            return alert(JSON.stringify(thisRow, null, 4));
          };
    
          return <Button onClick={onClick}>Click</Button>;
        }
      },
    ];
    

    Edit 64331095/cant-add-a-button-to-every-row-in-material-ui-table