I'm trying to create quantity section with reactjs but this is working only for one section. How can I make it multiple.
When I'm click on up arrow then count is increasing same in all the {qty}. but I need when I'll click on up arrow then it should be count as per the products.
Problem:- count is coming same:

Solution:- count should not same it should be like given below:

My Code:-
const BuyProducts = () => {
const title = 'Buy Products New';
const classes = productsStyles();
const [qty, setQty] = useState(0);
const quantityMinus = () => {
if (!qty == 0) {
setQty(qty - 1);
}
};
const quantityPlus = () => {
setQty(qty + 1);
};
return (
<div>
<div>
<div onClick={quantityPlus} className="qty-action">
<FontAwesomeIcon icon={faAngleUp} />
</div>
<div>{qty}</div>
<div onClick={quantityMinus} className="qty-action">
<FontAwesomeIcon icon={faAngleDown} />
</div>
</div>
<div>
<div onClick={quantityPlus} className="qty-action">
<FontAwesomeIcon icon={faAngleUp} />
</div>
<div>{qty}</div>
<div onClick={quantityMinus} className="qty-action">
<FontAwesomeIcon icon={faAngleDown} />
</div>
</div>
</div>
);
};
Thanks for your efforts!
You'll want to create some form of a data structure to manage multiple quantities. Since you're only using one qty variable right now, only one thing will ever change.
Let's say you have a simple CartItem interface to represent some shopping cart item that has quantity + a name or id of the item being purchased.
(It could look something like this if you were using typescript.)
interface CartItem {
name: string;
quantity: number;
}
Then in React, you'd want to store a collection of these CartItems in your state somewhere so you can track how many objects you need to render. You could use an object, set, or just a simple array depending on your use case. Let's use an array.
const [cartItems, setCartItems] = useState([{name: 'apple', quantity: 0}, {name: 'orange', quantity: 1}]); // initial data as an example
Next, your quantityUp/down functions need to be a little bit more generic so that they can receive a CartItem object as an argument and you can accordingly use that to figure out which cart item to update.
const changeQuantity = useCallback((item, quantityChange) => {
// Find the item to update
const oldCartItems = [...cartItems];
const itemIndex = oldCartItems.findIndex((oldItem) => oldItem.name === item.name);
// Change the quantity
oldCartItems[itemIndex].quantity += quantityChange;
// Put it back in state
setCartItems(oldCartItems);
}, [cartItems]);
Finally, in your rendering/JSX, you don't need to keep writing the same JSX over and over again. You can map through the cartItems state.
return (
<div>
{cartItems.map((cartItem) =>
<div>
<div onClick={() => changeQuantity(cartItem, 1)} className="qty-action">
<FontAwesomeIcon icon={faAngleUp} />
</div>
<div>{cartItem.quantity}</div>
<div onClick={() => changeQuantity(cartItem, -1)} className="qty-action">
<FontAwesomeIcon icon={faAngleDown} />
</div>
</div>
}
</div>
);