coder_coder123
coder_coder123

Reputation: 111

How to delete a specific row in Material UI DataGrid (Reactjs)

I'm starting this project in react & currently it's going well. However, I'm having an issue.

My desired functionality is this: I desire to delete every row that you see where the checkbox for that row is clicked. For example, if I click the checkbox in rows 1 & 3, I want rows 1 & 3 to be deleted. I also want to keep track of the rows that I decide to delete.

The issue is that I have no idea how to do that, and even after doing research I still feel stuck on how to approach this problem.

Currently I'm populating this table with some sample JSON data I found online, so don't mind the weird data that's present. Also, if anybody has recommendations for an easier or cleaner way to achieve this, then feel free to let me know about it in the comments.

Here's the code:

import React, { Component } from 'react';
import { DataGrid } from '@material-ui/data-grid';
import Button from '@material-ui/core/Button';


const columns = [
    { field: 'id', headerName: 'ID', width: 70 },
    { field: 'firstName', headerName: 'First name', width: 130 },
    { field: 'lastName', headerName: 'Last name', width: 130 },
    {
      field: 'age',
      headerName: 'Age',
      type: 'number',
      width: 90,
    },
    {
      field: 'fullName',
      headerName: 'Full name',
      description: 'This column has a value getter and is not sortable.',
      sortable: false,
      width: 160,
      valueGetter: (params) =>
        `${params.getValue('firstName') || ''} ${params.getValue('lastName') || ''}`,
    },
    { field: 'city', headerName: 'City', width: 100 },
    { field: 'state', headerName: 'State', width: 100 },
  ];
  
  const rows = [
    { id: 1, lastName: 'Snow', firstName: 'Jon', age: 35, city: 'Milwaukee', state: 'Wisconsin' },
    { id: 2, lastName: 'Lannister', firstName: 'Cersei', age: 42, city: 'Dubuque', state: 'Iowa' },
    { id: 3, lastName: 'Lannister', firstName: 'Jaime', age: 45, city: 'Appleton', state: 'Wisconsin'},
    { id: 4, lastName: 'Stark', firstName: 'Arya', age: 16, city: 'Madison', state: 'Wisconsin' },
    { id: 5, lastName: 'Targaryenmnsdlfbsjbgjksbgksbfksfgbk', firstName: 'Daenerys', age: null, city: 'Green Bay', state: 'Wisconsin' },
    { id: 6, lastName: 'Melisandre', firstName: null, age: 150, city: 'San Antonio', state: 'Texas' }, 
    { id: 7, lastName: 'Clifford', firstName: 'Ferrara', age: 44, city: 'Dallas', state: 'Texas' },
    { id: 8, lastName: 'Frances', firstName: 'Rossini', age: 36, city: 'Brooklyn', state: 'New York' },
    { id: 9, lastName: 'Roxie', firstName: 'Harvey', age: 65, city: 'Toledo', state: 'Ohio' },
    { id: 10, lastName: 'Larry', firstName: 'King', age: 105, city: 'Chicago', state: 'Illiniois' },
    { id: 11, lastName: 'Snow', firstName: 'Jon', age: 35, city: 'Milwaukee', state: 'Wisconsin' },
    { id: 12, lastName: 'Lannister', firstName: 'Cersei', age: 42, city: 'Dubuque', state: 'Iowa' },
    { id: 13, lastName: 'Lannister', firstName: 'Jaime', age: 45, city: 'Appleton', state: 'Wisconsin'},
    { id: 14, lastName: 'Stark', firstName: 'Arya', age: 16, city: 'Madison', state: 'Wisconsin' },
    { id: 15, lastName: 'Targaryenmnsdlfbsjbgjksbgksbfksfgbk', firstName: 'Daenerys', age: null, city: 'Green Bay', state: 'Wisconsin' },
    { id: 16, lastName: 'Melisandre', firstName: null, age: 150, city: 'San Antonio', state: 'Texas' }, 
    { id: 17, lastName: 'Clifford', firstName: 'Ferrara', age: 44, city: 'Dallas', state: 'Texas' },
    { id: 18, lastName: 'Frances', firstName: 'Rossini', age: 36, city: 'Brooklyn', state: 'New York' },
    { id: 19, lastName: 'Roxie', firstName: 'Harvey', age: 65, city: 'Toledo', state: 'Ohio' },
    { id: 20, lastName: 'Larry', firstName: 'King', age: 105, city: 'Chicago', state: 'Illiniois' },
  ];

class ElgibleContracts extends Component {
    render(){
        return (
            <div style={{textAlign: "center"}}>
                <h1 style={{fontFamily: "Stone"}}>Elgible Contracts</h1>
                <span className="horizontal-line" />
                <div className="centerDiv" style={{ height: 380, width: 950}}>
                    <DataGrid rows={rows} columns={columns} pageSize={10} checkboxSelection />
                </div>
                <br />
                <Button variant="contained" color="primary" onClick={this.getInfo} >Purge</Button>
            </div>
        )
    }
}

export default ElgibleContracts;

The Screen that's displayed

Upvotes: 1

Views: 17414

Answers (3)

Benny Code
Benny Code

Reputation: 54802

The usage of onRowSelected can end up in errors quickly because you have to reset the deletedRows when unselecting items in the DataGrid. That's why I suggest to make use of onSelectionModelChange:

const [rows, setRows] = useState(data);
const [deletedRows, setDeletedRows] = useState([]);

<DataGrid
  checkboxSelection
  columns={columns}
  pageSize={5}
  onSelectionModelChange={({selectionModel}) => {
    const rowIds = selectionModel.map(rowId => parseInt(String(rowId), 10));
    const rowsToDelete = rows.filter(row => rowIds.includes(row.id));
    setDeletedRows(rowsToDelete);
  }}
  rows={rows}
/>

Upvotes: 0

EVeras
EVeras

Reputation: 324

I created a sandbox for this: https://codesandbox.io/s/heuristic-davinci-n3vrz?file=/src/App.js

I used functional components and hooks since this is best practice nowadays.

   const [rows, setRows] = useState(data);
   const [deletedRows, setDeletedRows] = useState([]);

   const handleRowSelection = (e) => {
    setDeletedRows([...deletedRows, ...rows.filter((r) => r.id === e.data.id)]);
  };

  const handlePurge = () => {
    setRows(
      rows.filter((r) => deletedRows.filter((sr) => sr.id === r.id).length < 1)
    );
  };

  return (
    <div style={{ textAlign: "center" }}>
      <h1 style={{ fontFamily: "Stone" }}>Elgible Contracts</h1>
      <span className="horizontal-line" />
      <div className="centerDiv" style={{ height: 380, width: 950 }}>
        <DataGrid
          rows={rows}
          columns={columns}
          pageSize={10}
          checkboxSelection
          onRowSelected={handleRowSelection}
        />
      </div>
      <br />
      <Button variant="contained" color="primary" onClick={handlePurge}>
        Purge
      </Button>

Upvotes: 3

DamianM
DamianM

Reputation: 498

const ElgibleContracts = () => {
  const [items, setItems] = React.useState(rows)
  const [selection, setSelection] = React.useState([]);
  const [deleted, setDeleted] = React.useState([])
  const handlePurge = () => {
    setDeleted([...deleted, ...selection])
    setItems(items.filter(i=> !selection.some(s=> s.id === i.id)))
    setSelection([])
  }
  console.log("Here are deleted items",deleted)
        return (
            <div style={{textAlign: "center"}}>
                <h1 style={{fontFamily: "Stone"}}>Elgible Contracts</h1>
                <span className="horizontal-line" />
                <div className="centerDiv" style={{ height: 380, width: 950}}>
                    <DataGrid  onSelectionChange={(newSelection) => {
          setSelection(newSelection.rows);
        }} rows={items} columns={columns} pageSize={10} checkboxSelection />
                </div>
                <br />
                <Button variant="contained" color="primary" onClick={handlePurge} >Purge</Button>
            </div>
        )
    }

Upvotes: 1

Related Questions