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

Viewed 2393

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>
            )
        })
    }
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.

Related