Loading lessons...
Project 3: E-Commerce Shopping Cart
Project 3: E-Commerce Shopping Cart
In this project, you will build a Shopping Cart Application using the Context API (createContext, useContext) to manage global cart state across product catalog and cart drawer components.
Project Specifications
Your application will:
- Maintain global cart items state inside
CartContext. - Add products to cart, update item quantities, and remove items.
- Compute cart total item counts and grand total price dynamically.
import { createContext, useContext, useState } from 'react';
// 1. Create Context
const CartContext = createContext();
export function CartProvider({ children }) {
const [cart, setCart] = useState([]);
const addToCart = (product) => {
setCart(prev => {
const existing = prev.find(item => item.id === product.id);
if (existing) {
return prev.map(item =>
item.id === product.id ? { ...item, quantity: item.quantity + 1 } : item
);
}
return [...prev, { ...product, quantity: 1 }];
});
};
const updateQuantity = (id, delta) => {
setCart(prev =>
prev
.map(item =>
item.id === id ? { ...item, quantity: item.quantity + delta } : item
)
.filter(item => item.quantity > 0)
);
};
const totalCost = cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
return (
<CartContext.Provider value={{ cart, addToCart, updateQuantity, totalCost, totalItems }}>
{children}
</CartContext.Provider>
);
}
export const useCart = () => useContext(CartContext);
// 2. Product Catalog Component
export function ProductList({ products }) {
const { addToCart } = useCart();
return (
<div className="product-grid">
{products.map(p => (
<div key={p.id} className="product-card">
<h4>{p.name}</h4>
<p>${p.price}</p>
<button onClick={() => addToCart(p)}>Add to Cart</button>
</div>
))}
</div>
);
}
Summary & TL;DR
- Use Context API for global application state like shopping carts.
- Use
array.reduce()to calculate derived totals without extra state variables. - Update quantities immutably and filter out zero-quantity items.