Home > Back-end >  How do I delete a specific row in a table in reactjs?
How do I delete a specific row in a table in reactjs?

Time:10-08

My last question was about deleting all rows in a table which is solved. The problem I am now having is how I would go abouts deleting a specific row which has a delete button on it. What I am trying to achieve is that when the button is clicked, that row which the button is on deleted.

The issue I am having now is that when I press the delete button on the row, it deletes the very first row on the table which is not what I want.

const [shop, setShop] = useState([]);
....
function singleDelete(i){
        var newArr = [...shop];
        newArr.splice(i, 1);
        setShop(newArr);
        setCount(count -1);
  }
      

CodePudding user response:

You can use Array.prototype.filter:

setShop(shop.filter((_, index) => index !== i));

Also, don't maintain a separate count variable as it is redundant. The count can easily be retrieved with shop.length.

CodePudding user response:

Using filter: setShop(shop.filter((_, shopIndex) = shopIndex !== i));

CodePudding user response:

Created working example here, you can use this sandbox Link: https://codepen.io/naveenkumarpg/pen/GRvKpxM

for the reference you can take row id and delete the item.

remove = (rowId) => {
    // Array.prototype.filter returns new array
    // so we aren't mutating state here
    const arrayCopy = this.state.data.filter((row) => row.id !== rowId);
    this.setState({data: arrayCopy});
};
  • Related