2

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 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

didn't work, it deletes the last object in that array instead but not the wanted index

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.