reactjsdatagridmaterial-ui

MUI: How to delete selected rows in DataGrid programmatically?


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:

enter image description here

After I press the delete button:

enter image description here

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)
    }
  />

Solution

  • 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
    />
    

    Live Demo

    Edit 67209637/how-to-reset-the-check-box-in-material-ui-data-grid-programmatically