-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcartFunctionality.js
More file actions
65 lines (51 loc) · 1.37 KB
/
Copy pathcartFunctionality.js
File metadata and controls
65 lines (51 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { useState } from "react";
const products = [
{ id: 1, name: "Laptop", price: 50000 },
{ id: 2, name: "Mouse", price: 1000 },
];
export default function CartExample() {
const [cart, setCart] = useState([]);
const addToCart = (product) => {
setCart((prev) => {
const existingItem = prev.find((item) => item.id === product.id);
if (existingItem) {
return prev.map((item) =>
item.id === product.id
? { ...item, quantity: item.quantity + 1 }
: item
);
}
return [...prev, { ...product, quantity: 1 }];
});
};
const removeFromCart = (id) => {
setCart((prev) => prev.filter((item) => item.id !== id));
};
const total = cart.reduce(
(sum, item) => sum + item.price * item.quantity,
0
);
return (
<div>
<h2>Products</h2>
{products.map((product) => (
<div key={product.id}>
<span>
{product.name} - ₹{product.price}
</span>
<button onClick={() => addToCart(product)}>Add</button>
</div>
))}
<h2>Cart</h2>
{cart.map((item) => (
<div key={item.id}>
<span>
{item.name} x {item.quantity}
</span>
<button onClick={() => removeFromCart(item.id)}>Remove</button>
</div>
))}
<h3>Total: ₹{total}</h3>
</div>
);
}