Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete objects from react state hook array with a button click

I'm trying to make a button that deleted an object from an array (which is the state) depending on the passed index, I've tried alot but none of my ways worked :( , so this is the code and hope i can find someone to help:

state:

const [items, setItems] = useState([{ name: "", quantity: "", unit: "" }]);

deleting function:

const deleteItem = (i) => {
    const newItems = [...items]
    newItems.splice(i, 1)
    setItems(newItems)
}

jsx elements:

    {
        items.map((item, i) => {
            return (
                <div key={i} className={`mt3 item-input-wrapper`}>
                    <div>some other els here</div>
                    <button onClick={() => deleteItem(i)} >delete item</button>
                </div>
            )
        })
    }
like image 529
Salah Eddine Makdour Avatar asked Aug 03 '26 05:08

Salah Eddine Makdour


1 Answers

You can do it with filter:

const deleteItem = (i) => {
  setItems(currentItems => currentItems.filter((item, index) => index !== i));
}

Altho you'd probably use smth more constant for accessing an item, like an id.

like image 187
Clarity Avatar answered Aug 05 '26 20:08

Clarity



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!