How to delete multiple selected rows in Material-UI DataGrid?

All we need is an easy explanation of the problem, so here it is.

I wanna know how to delete rows from the DataGrid from Material-UI by using the checkboxes in React. I haven’t find any proper tutorial for doing this on DataGrid although I found one for MaterialTable but is not the same.

How to delete multiple selected rows in Material-UI DataGrid?

Any help is welcome.

UPDATE

My full code after adapt solution:

import React, { useState, useEffect, Fragment } from 'react'
import {db} from './firebase';
import { useHistory, useLocation } from 'react-router-dom';
import "./ListadoEstudiantes.css"
import * as locales from '@mui/material/locale';
import { DataGrid, 
  GridRowsProp, GridColDef,
  GridToolbarContainer, GridToolbarColumnsButton, GridToolbarFilterButton, GridToolbarExport, GridToolbarDensitySelector} from '@mui/x-data-grid';
import { Button, Container } from "@material-ui/core";
import { IconButton} from '@mui/material';
import PersonAddIcon from '@mui/icons-material/PersonAddSharp';
import DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined';
import { Box } from '@mui/system';

function ListadoEstudiantes({user}) {

  const history = useHistory("");
  const crearEstudiante = () => {
    history.push("/Crear_Estudiante");
  };

 const [estudiantesData, setEstudiantesData] = useState([])

 const parseData = {
  pathname: '/Crear_Pedidos',
  data: estudiantesData
}

const realizarPedidos = () => {
  if(estudiantesData == 0)
  {
    window.alert("Seleccione al menos un estudiante")
  }
  else {
    history.push(estudiantesData);
  }
};

 function CustomToolbar() {
  return (
    <GridToolbarContainer>
      <GridToolbarFilterButton />
      <GridToolbarDensitySelector />
    </GridToolbarContainer>
  );
}


const [estudiantes, setEstudiantes] = useState([]);
  const [selectionModel, setSelectionModel] = useState([]);
  const columns = [
    { field: 'id', headerName: 'ID', width: 100 },

  {field: 'nombre', headerName: 'Nombre', width: 200},

  {field: 'colegio', headerName: 'Colegio', width: 250},

  {field: 'grado', headerName: 'Grado', width: 150},
    {
      field: "delete",
      width: 75,
      sortable: false,
      disableColumnMenu: true,
      renderHeader: () => {
        return (
          <IconButton
            onClick={() => {
              const selectedIDs = new Set(selectionModel);
              setEstudiantes((r) => r.filter((x) => !selectedIDs.has(x.id)));
              
            }}
          >
            <DeleteOutlinedIcon />
          </IconButton>
        );
      }
    }
  ];

 const estudiantesRef = db.collection("usuarios").doc(user.uid).collection("estudiantes")
 useEffect(() => {
  estudiantesRef.onSnapshot(snapshot => {
    const tempData = [];
    snapshot.forEach((doc) => {
      const data = doc.data();
      tempData.push(data);
    });
    setEstudiantes(tempData);
  })
 }, []);

    return (
      <Container fixed>
      <Box mb={5} pt={2} sx={{textAlign:'center'}}>
      <Button
      startIcon = {<PersonAddIcon />} 
      variant = "contained" 
      color = "primary" 
      size = "medium" 
      onClick={crearEstudiante} >
      Crear Estudiantes
      </Button>
      <Box pl={25} pt={2} sx={{height: '390px', width: "850px", textAlign:'center'}}>
      <DataGrid
        rows={estudiantes}
        columns={columns}
        pageSize={5}
        rowsPerPageOptions={[5]}

        components={{
          Toolbar: CustomToolbar,
        }}

        checkboxSelection
        //Store Data from the row in another variable
        onSelectionModelChange = {(id) => {
          setSelectionModel(id);
          const selectedIDs = new Set(id);
          const selectedRowData = estudiantes.filter((row) =>
            selectedIDs.has(row.id)
          );
          setEstudiantesData(selectedRowData)
          console.log(estudiantesData);
        }
      }
        {...estudiantes}
        
      />
      </Box></Box></Container>
    )
}

export default ListadoEstudiantes

UPDATE
Everything works! thank you

How to delete multiple selected rows in Material-UI DataGrid?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can keep track of the currently selected IDs via selectionModel/onSelectionModelChange props, and perform the necessary action when the user click the IconButton on the header. Because renderHeader callback doesn’t provide the selection state, I have to make use of closure by putting the columns definition inside the function body so I can reference selectionModel in the callback:

const [rows, setRows] = React.useState(_rows);
const [selectionModel, setSelectionModel] = React.useState([]);
const columns: GridColDef[] = [
  { field: "col1", headerName: "Column 1", width: 150 },
  { field: "col2", headerName: "Column 2", width: 150 },
  {
    field: "delete",
    width: 75,
    sortable: false,
    disableColumnMenu: true,
    renderHeader: () => {
      return (
        <IconButton
          onClick={() => {
            const selectedIDs = new Set(selectionModel);
            // you can call an API to delete the selected IDs
            // and get the latest results after the deletion
            // then call setRows() to update the data locally here
            setRows((r) => r.filter((x) => !selectedIDs.has(x.id)));
          }}
        >
          <DeleteIcon />
        </IconButton>
      );
    }
  }
];

return (
  <div style={{ height: 400, width: "100%" }}>
    <DataGrid
      rows={rows}
      columns={columns}
      checkboxSelection
      onSelectionModelChange={(ids) => {
        setSelectionModel(ids);
      }}
    />
  </div>
);

How to delete multiple selected rows in Material-UI DataGrid?

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply