Data grid - Events
You can subscribe to the events emitted by the data grid to trigger custom behavior.
Subscribing to events
You can subscribe to one of the events emitted by providing an event handler to the grid.
The handler is a method that will be called with three arguments:
- the parameters containing the information related to the event
- the
MuiEvent
containing the DOM event or the React synthetic event, when available - the
GridCallbackDetails
containing theGridApi
, only ifDataGridPro
orDataGridPremium
is being used
For example, here is an event handler for the rowClick
event:
const handleEvent: GridEventListener<'rowClick'> = (
params, // GridRowParams
event, // MuiEvent<React.MouseEvent<HTMLElement>>
details, // GridCallbackDetails
) => {
setMessage(`Movie "${params.row.title}" clicked`);
};
You can provide this event handler to the grid in several ways:
With the prop of the event
<DataGrid onRowClick={handleEvent} {...other} />
The following demo shows how to subscribe to the rowClick
event using the onRowClick
prop—try it out by clicking on any row:
With useGridApiEventHandler
useGridApiEventHandler('rowClick', handleEvent);
The following demo shows how to subscribe to the rowClick
event using useGridApiEventHandler
—try it out by clicking on any row:
With apiRef.current.subscribeEvent
apiRef.current.subscribeEvent('rowClick', handleEvent);
The following demo shows how to subscribe to the rowClick
event using apiRef.current.subscribeEvent
—try it out by clicking on any row:
Disabling the default behavior
Depending on the use case, it might be necessary to disable the default action taken by an event.
The MuiEvent
passed to the event handler has a defaultMuiPrevented
property to control when the default behavior can be executed or not.
Set it to true
to block the default handling of an event and implement your own.
<DataGrid
onCellClick={(params: GridCellParams, event: MuiEvent<React.MouseEvent>) => {
event.defaultMuiPrevented = true;
}}
/>
Usually, double clicking a cell will put it into edit mode. The following example changes this behavior by also requiring Ctrl to be pressed.