I'm creating a file list with MUI DataGrid
. The user able to check the checkbox in DataGrid
to make their selection. I want the checkbox to reset after the user perform some action such as delete the selected file.
The problem I'm facing is after I perform the delete action, the checkbox are still checked in the same spot. For example before I press the delete button:
After I press the delete button:
The checkbox are still checked on the second row. How do I reset the checkbox programmatically?
const [selectedFile, setSelectedFile] = useState([]); // To keep selected file
const [files, setFiles] = useState([]); // To keep uploaded file
const deleteSelectedFile = () => {
const filteredFileList = files.filter(
(item) => !selectedFile.includes(item)
);
setFiles(filteredFileList);
};
<DataGrid
rows={displayFile ? displayFile : []}
columns={columns}
pageSize={3}
checkboxSelection
onSelectionModelChange={({ selectionModel }) =>
setSelectedFile(selectionModel)
}
/>
selectionModel
is not an array of RowData
, but RowId
, so in your delete handler, you need to check if the selectionModel
includes an item.id
, not item
:
const deleteSelectedFile = () => {
const filteredFileList = files.filter(
(item) => !selectedFile.includes(item.id)
);
setFiles(filteredFileList);
};
And because you're using controlled selection, you need to provide the selectionModel
props to the DataGrid
too:
const [selectionModel, setSelectionModel] = React.useState([]);
<DataGrid
{...props}
onSelectionModelChange={setSelectionModel}
selectionModel={selectionModel} // add this line
/>