Home > front end >  How to delete a row in a Material UI table?
How to delete a row in a Material UI table?

Time:07-28

I am creating a crud table using React and Materials UI.I was wondering how I can delete a row of a table.I am fetching data from a API and displaying into a table,but I don't know how can I delete a row from a button. This is my first react project so sorry!Thank you!

Part from Component Table code:

   <TableBody>
              {posts.slice(0,6).map((post) => (
                <StyledTableRow key={post.id}>
              <StyledTableCell component="th" scope="row">{post.title}</StyledTableCell>
              <StyledTableCell align="center">{post.body}</StyledTableCell>
              <StyledTableCell align="center"><DialogBoxEdit dataParent1={post.title} dataParent2={post.body} /></StyledTableCell>
              <StyledTableCell align="center"><Button variant="outlined" color="error" onClick={handleClick}>Delete</Button></StyledTableCell>
            </StyledTableRow>
          ))}
        </TableBody>

Handle Delete:

  const handleClick = (e) => {
    e.preventDefault();
    console.log('The delete was clicked');
  }

Imports:

import * as React from 'react';
import { styled } from '@mui/material/styles';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell, { tableCellClasses } from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Paper from '@mui/material/Paper';
import { Button } from '@mui/material';
import './App.css';
import { useEffect, useState } from "react";
import  DialogBoxEdit from './DialogBoxEdit';

Fetching data from API,that are inserted in table:

 const [posts, setPosts] = useState([])

  const fetchData = () => {

    fetch("https://jsonplaceholder.typicode.com/posts").then(response => {

        return response.json()

      })

      .then(data => {

        setPosts(data)

      })

  }


  useEffect(() => {

    fetchData()

  }, [])

CodePudding user response:

You can pass the post index and filter out the deleted item and update the posts state.

  1. Define a delete handler function as below using the callback of setter of useState hook for posts:
  const handleDelete = (postIndex) => {
    setPosts((prevPosts) =>
      prevPosts.filter((_, index) => index !== postIndex)
    );
  };
  1. Pass the index of the post that is going to be deleted to the delete handler:
    <TableBody>
      {posts.map((post, postIndex) => (
        <TableRow key={post.id}>
          ...
          ...
          <TableCell align="center">
            <Button
              variant="outlined"
              color="error"
              onClick={() => handleDelete(postIndex)}
            >
              Delete
            </Button>
          </TableCell>
        </TableRow>
      ))}
    </TableBody>

Codesandbox:

Edit delete a row in a Material UI table

  • Related