Home > Blockchain >  How to remove table row on click in reactjs?
How to remove table row on click in reactjs?

Time:10-08

This is an addon to my previous question; I am trying to delete a specific row when the button is clicked, however everytime the button is clicked it deletes the next table row instead of itself. Here is what it looks like with a video. The current code I am using to perform this action is:

const [shop, setShop] = useState([]);

const singleDelete = (d) => {
        const newArr = [...shop];
        const index = shop.findIndex((contact) => contact.id === d);
        newArr.splice(index, 1);
        setShop(newArr);
}

return (
        <div className="content">
         <Table>
            <tbody id="tbid">
                    
                      {(shop.map((s,i) => (
                        <tr key={`${s i}`} id={i} value={`${i}Row`}>
                        <td>{i}</td>
                        <td>{profil[i]}</td>
                        <td>{s}</td>
                        <td></td>
                        <td>{acc[i]}</td>
                        <td>
                        <Button className="btn-round btn-icon" color="danger" size="sm" type="submit" onClick={singleDelete}>
                              <i className="icon-simple-delete"/>
                          </Button>
                        </td>
                        </tr>
                      )))}
                    </tbody>    
         </Table>
        <div>
)

I have tried using setShop(shop.filter((_, index) => index !== d)); But the results are still the same.

CodePudding user response:

The problem is you don't pass the ID into the singleDelete function.

Change this:

onClick={singleDelete}

to this:

onClick={ () => singleDelete(s.id) }

And it would be nice to rewrite singleDelete function like @stoen recommended.

CodePudding user response:

Maybe try using filter instead:

const singleDelete = (d) => {
    setShop(shop.filter((contact) => contact.id !== d));
}
  • Related