Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

270
Vistas
How to delete a row in a Material UI table?

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()

  }, [])
about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda