Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS - How to remove an item from an array in a functional component?

I am trying to create a simple shopping cart using ReactJS and I figured a potential way out but whenever I click on the remove button I've set it doesn't really remove the items from the cart.. So those are my state managers right here:

let[product, setProduct] = useState([])
//The function bellow is what I use to render the products to the user
const[item] = useState([{
        name: 'Burger',
        image: '/static/media/Burger.bcd6f0a3.png',
        id: 0,
        price: 16.00
    },
    {
        name: 'Pizza',
        image: '/static/media/Pizza.07b5b3c1.png',
        id: 1,
        price: 20.00
    }])

and I have a function that adds the objects in item to the product array, then I have a function that is supposed to remove them that looks like this:

    const removeItem=(idx)=>
{
    // let newProduct = product.splice(idx,1)
    // setProduct([product,newProduct])
    // $('.showItems').text(product.length)
    // product[idx]=[]
    product.splice(idx,1)

    if(product.length<=0)
    {
        $('.yourCart').hide()
    }
}

This function is called from here:

                    {product.map((item, idx)=>
                <div className='yourCart' key={idx}>
                    <hr></hr>
                    <div>
                        <img src ={item.image}></img>
                        <h3 className='burgerTitle'>{item.name}</h3>
                        <h4><strong>$ {item.price}.00</strong></h4>
                        <Button variant='danger' onClick={()=>removeItem(idx)}>Remove</Button>
                    </div>
                    <br></br>
              </div>)}

The problem is that I've tried to use splice, setState, I tried to even clear the entire array and add the elements that are left after applying the filter function to it but it was all to no avail. How can I make it so that when I click on the remove button it removes the specific item from the array??

like image 768
Python_Mython79 Avatar asked Oct 25 '25 02:10

Python_Mython79


1 Answers

You can define removeItem as a function, which gets an id (instead of an index, since that's safer) and setProduct to the subset which should remain. This could be achieved in many ways, in this specific example I use .filter() to find the subset of product whose elements differ in their id from the one that is to be removed and set the result as the new value of product.

removeItem = (id) => {
  setProduct(product.filter((i)=>(i.id !== id)))
 
}
like image 173
kuna thana Avatar answered Oct 27 '25 15:10

kuna thana