The user selects multiple cells in a data grid and hits the delete
key. they expect all values to be set to NULL.
However, only the first cell is cleared. The user expects to replicate the behavior in Excel.
Not sure how much additional code I can provide to clarify this question -- for the most part this implementation is pretty standard. The specific data type or rendering of cells should not matter, right?
The user selects multiple cells in a data grid and hits the delete
key. they expect all values to be set to NULL.
However, only the first cell is cleared. The user expects to replicate the behavior in Excel.
Not sure how much additional code I can provide to clarify this question -- for the most part this implementation is pretty standard. The specific data type or rendering of cells should not matter, right?
Share Improve this question edited Mar 22 at 13:39 Raghavendra N 9,1801 gold badge24 silver badges41 bronze badges asked Mar 19 at 16:37 ShaunLangleyShaunLangley 3341 gold badge4 silver badges14 bronze badges 1- This behavior has been documented github/mui/mui-x/issues/11982. I'm looking for a workaround until the enhancement is adopted. – ShaunLangley Commented Mar 19 at 19:03
1 Answer
Reset to default 2 +50I found a way to get this done. When the Delete key is pressed you need to get the selected cells and set their values to NULL. Since you are only deleting the values, you don't even have to call the setEditCellValue
. startCellEditMode
has third parameter deleteValue
, which when set to true will delete the cell value being focused. So here are the steps:
onCellKeyDown
callback get the selected cells usinggetCellSelectionModel
- For each selected cell, call
startCellEditMode
withdeleteValue
set to true.
Example code:
import * as React from 'react';
import { DataGridPremium, useGridApiRef } from '@mui/x-data-grid-premium';
import { useDemoData } from '@mui/x-data-grid-generator';
export default function CellSelectionGrid() {
const { data } = useDemoData({
dataSet: 'Commodity',
rowLength: 10,
maxColumns: 6,
editable: true,
});
const apiRef = useGridApiRef();
const onCellKeyDown = async (params, e) => {
if (e.key !== 'Delete') return;
Object.keys(apiRef.current.getCellSelectionModel()).forEach(
async (rowId) => {
Object.keys(apiRef.current.getCellSelectionModel()[rowId]).forEach(
async (field) => {
await apiRef.current.startCellEditMode({
id: rowId,
field: field,
deleteValue: true,
});
}
);
}
);
};
return (
<div style={{ width: '100%', height: 400 }}>
<DataGridPremium
apiRef={apiRef}
cellSelection
{...data}
onCellKeyDown={onCellKeyDown}
/>
</div>
);
}
Check this StackBlitz demo.