Search code examples
reactjsdatagridmaterial-ui

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


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.

enter image description here

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

enter image description here


Solution

  • 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>
    );
    

    Codesandbox Demo