Delete Row on Remove Click React

Delete row from a table, deleteRow(id), remove() or use useState () in Reactjs

Best practice is to manage data through state, I would suggest not to do DOM manipulation manually

export default function App() {
const [data, setData] = useState(['Eli','Smith', 'Jhon']);
const handleDelete = (index,e) => {
setData(data.filter((v, i) => i !== index));
}
const rows = data.map((item, index) => {
return (
<tr key={index}>
<td>{item}</td>
<td><button onClick={e => handleDelete(index,e)}>Delete</button></td>
</tr>
)
})
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<table>
{rows}
</table>
</div>
);
}

how to delete a row from the table with a button on react?

You should not be manipulating the DOM as this is an anti-pattern in React, instead you should update the state you are rendering from.

Delete by idFoto.

deleteRow = (idFoto)=> {
this.setState(prevState => ({
fotos: prevState.fotos.filter(el => el.idFoto !== idFoto
}))
}

In the child pass the id to the delete handler.

<button className="btn btn-outline-danger" 
onClick={() => props.restauranteAremover(row.idFoto)}>
Delete restaurante
</button>

How to delete a row from a HTML table with React?

The better way to implement this will be to display using an Array and giving ids to individual row items ->

Your code will be something like this then ->

const [dataArray, setDataArray] = useState([
{ name: "Valles Caldera National Preserve", id: 1 },
{ name: "Tyler Morales", id: 2 },
]);

const removeSite = async (id) => {
setDataArray((data) => data.filter((dataEach) => dataEach.id !== id));
};

return (
<table>
<tbody>
<tr>
<th>Name</th>
</tr>
{dataArray.map((data) => (
<tr key={data.id}>
<td>{data.name}</td>
<button onClick={(e) => removeSite(data.id)}>Delete</button>
</tr>
))}
</tbody>
</table>
);

Remove row from antd table on row button click

Looks to possibly be a stale enclosure of your data state. I suggest trying a functional state update instead. The functional state update will update from the previous state instead of using what is closed over in any callback scope.

const handleDelete = (stid) => {
setData(data => data.filter(item => item.studentId !== stid));
};

How to delete item on click in React

You should move your deleteItem and MyCommandCell functions inside your App component in order to to use setData. You also need to read current row's data from dataItem of current row's item. That value should be passed to the deleteItem function as a prop

You can use this code:

import * as React from "react";
import * as ReactDOM from "react-dom";
import { Grid, GridColumn as Column } from "@progress/kendo-react-grid";
import { sampleProducts } from "./sample-products";

const allInEdit = sampleProducts.map((item) =>
Object.assign(
{
inEdit: true
},
item
)
);

const App = () => {
const [data, setData] = React.useState(allInEdit);

const deleteItem = (item) => {
let newProducts = data.filter(
(record) => record.ProductID !== item.ProductID
);
setData(newProducts);
};

const MyCommandCell = (item) => {
return (
<button
className="k-button k-grid-remove-command"
onClick={() => deleteItem(item.dataItem)}
>
Remove
</button>
);
};

const itemChange = (e) => {
let newData = data.map((item) => {
if (item.ProductID === e.dataItem.ProductID) {
item[e.field || ""] = e.value;
}

return item;
});
setData(newData);
};

return (
<Grid data={data} editField="inEdit" onItemChange={itemChange}>
<Column field="ProductID" title="Id" width="50px" editable={false} />
<Column field="ProductName" />
<Column field="FirstOrderedOn" editor="date" format="{0:d}" />
<Column field="UnitsInStock" width="150px" />
<Column field="Discontinued" width="50px" editor="boolean" />
<Column cell={MyCommandCell} width="240px" />
</Grid>
);
};

ReactDOM.render(<App />, document.querySelector("my-app"));

You can take a look at this sandbox for live working example.

Remove a specific table row on onClick event in React component

Create a delete function and then send the index of the array into that and use splice to remove that array entry. Pass reference to this deleteRow function to the child component and call it from there like this.props.deleteRow(this.props.index); .Check out the complete code

like

deleteRow: function(index) {
var contacts = [...this.state.contacts];
contacts.splice(index, 1);
this.setState({contacts});
},

var ContactAll = React.createClass({  getInitialState: function() {    return {      contacts: []     }  },  componentDidMount: function() {    $.ajax({      dataType: "json",      url: '/all-contacts',      type: "GET",      context: this,      success: function(data, status, xhr) {        this.setState({ contacts: data });      }    });  },  deleteRow: function(index) {    var contacts = [...this.state.contacts];    contacts.splice(index, 1);    this.setState({contacts});  },  render: function(){    if(this.state.contacts == 0) {      return (        <div>Loading</div>      )    } else {      var contactComponents = this.state.contacts.map(function(contact, i) {        var full_name = contact.first_name + ' ' + contact.last_name
return <tr key={i} className="contact"> <td>{ full_name}</td> <td></td> <td>{ contact.email_address }</td> <td>{ contact.phone_number }</td> <td>{ contact.company_name }</td> <td><DeleteButton onClick ={this.deleteRow.bind(this)} index={i} email={contact.email_address} /></td> </tr>; }.bind(this)); return <div> <table> <tbody> <tr> <th>Contact Name</th> <th></th> <th>Email Address</th> <th>Phone Number</th> <th>Company Name</th> </tr>
{contactComponents};
</tbody> </table> </div> } }}); var DeleteButton = React.createClass({ onClick: function() { var email = this.props.email; this.props.deleteRow(this.props.index); $.ajax({ data: {email_address: email }, url: '/delete-contact', dataType: 'html', type: "POST", success: function(data, status, xhr) { $('.delete-success').slideDown(400); setTimeout(function() { $(".delete-success").slideUp(400); }, 5000); } }); }, render: function(){ return( <button onClick={() => { this.onClick(this.props.email) }}>Delete</button> ) }});

How to delete all rows on click in a dynamic table using reactjs

set it as empty array

setShop([ ])

React table row delete does not remove the TextInput

When using lists React expects a "key" prop so that when an a child e.g. a book is deleted it knows which one was deleted

I am having a hard time following your code but your books should like this in the list:

<tr key={book.id}>
<td>whatever</td>
</tr>

now when the tr with the key of {some id} at index 4 for example is deleted react will update the list correctly

Deleting a targeted row in function component React

Is there any reason not to use array.prototype.filter() just like you've done in your Class Component? This seems more readable and ensures you avoid mutating state directly in fewer steps.

Here is what that would look like in your handleDelete function in FunctionComponent:

const handleDelete = (id) => {
setList(list.filter((row) => (
row.id !== id
)));
};


Related Topics



Leave a reply



Submit