i have an array like this
const products = [
{ id: 1, name: "Apple", price: 10, img: "apple.jpg" },
{ id: 2, name: "Banana", price: 20, img: "banana.jpg" },
{ id: 3, name: "Cherry", price: 30, img: "cherry.jpg" }
];
const [cartItem, setCartItem] = usestate([])
const [quantity, setQuantity] = useState(1)
const handleAdd = () => {
setQuantity(quantity + 1)
}
const handleReduce = () => {
setQuantity(quantity - 1)
}
<div>
{cartItem.map((item) => {
return(
<div>
<button onClick={()=>handleAdd()}>ADD</button>
<img src={item.IMG} alt="" />
<h3 className="name">{item.product}</h3>
<p className="price">{item.price}</p>
<p className="quantity">{quantity}</p>
<button onClick={()=>handleReduce()}>REMOVE</button>
</div>
)
})}
</div>
when i add the object from products array to cartItem, and rendered it, i've got a few elements from the cartItem. I want to know how to add and reduce the quantity from the specific items
import { useState } from "react";
import products from "./src/components/products";
const Cart = () => {
const [cartItem, setCartItem] = usestate([])
*The cartItem was a context*
const [quantity, setQuantity] = useState(1)
const handleAdd = () => {
setQuantity(quantity + 1)
}
const handleReduce = () => {
setQuantity(quantity - 1)
}
return(
<>
<div>
{cartItem.map((item) => {
return(
<div>
<button onClick={()=>handleAdd()}>ADD</button>
<img src={item.IMG} alt="" />
<h3 className="name">{item.product}</h3>
<p className="price">{item.price}</p>
<p className="quantity">{quantity}</p>
<button onClick={()=>handleReduce()}>REMOVE</button>
</div>
)
})}
</div>
</>
)
};
export default Cart
i've been trying something like this, but when i click add button, instead of add an specific element it also add a quantity from all the elements
please help, i'm really new to React