MaterialUI (MUI). How to pass handlers via props to DataGrid component (for using them in column type=actions)

Viewed 1951

The docs say: https://mui.com/components/data-grid/columns/

If the column type is 'actions', you need to provide a getActions function that returns an array of actions available for each row (React elements). You can add the showInMenu prop on the returned React elements to signal the data grid to group these actions inside a row menu.

{
  field: 'actions',
  type: 'actions',
  getActions: (params: GridRowParams) => [
    <GridActionsCellItem icon={...} onClick={...} label="Delete" />,
    <GridActionsCellItem icon={...} onClick={...} label="Print" showInMenu />,
  ]
}

How to pass via props onClick handlers?

<DataGrid deleteHandler={...} printHandler={...} /> 
2 Answers

I'm sorry for stupid question. Of course we can pass handlers in columns prop :))) But I have found even better solution. I don't use calback handlers in action column, but I use component.

getActions: (params: any) => [
                <GridActionsCellItem
                    icon={<OpenIcon />}
                    label='Open'
                    component={Link}
                    to={`/counterparties/${params.id}`}
                />

The docs actually explain how to add handler:

Visit Special properties then scroll down a bit then click Show the full source icon

Basically we need to declare columns inside our functional component where the handler resides, but wrap the columns array using useMemo() to prevent unnecessary rerender.

const columns = React.useMemo(
    () => [
      {
        field: 'actions',
        type: 'actions',
        width: 80,
        getActions: (params) => [
          <GridActionsCellItem
            icon={<DeleteIcon />}
            label="Delete"
            onClick={deleteUser(params.id)}
          />,
          <GridActionsCellItem
            icon={<SecurityIcon />}
            label="Toggle Admin"
            onClick={toggleAdmin(params.id)}
            showInMenu
          />,
          <GridActionsCellItem
            icon={<FileCopyIcon />}
            label="Duplicate User"
            onClick={duplicateUser(params.id)}
            showInMenu
          />,
        ],
      },
], [deleteUser, toggleAdmin, duplicateUser]);
Related