Here’s a simple example of a shopping cart page in a React application. In this example, we’ll create a basic shopping cart that allows users to add and remove items from their cart. We’ll use React’s state management to keep track of the cart’s contents.
import React, { useState } from 'react';
const CartPage = () => {
const [cart, setCart] = useState([]);
const [total, setTotal] = useState(0);
const addToCart = (item) => {
const updatedCart = [...cart, item];
setCart(updatedCart);
calculateTotal(updatedCart);
};
const removeFromCart = (itemToRemove) => {
const updatedCart = cart.filter((item) => item !== itemToRemove);
setCart(updatedCart);
calculateTotal(updatedCart);
};
const calculateTotal = (cartItems) => {
const totalPrice = cartItems.reduce((acc, item) => acc + item.price, 0);
setTotal(totalPrice);
};
return (
<div>
<h1>Shopping Cart</h1>
<div className="cart">
<h2>Cart Items</h2>
<ul>
{cart.map((item, index) => (
<li key={index}>
{item.name} - ${item.price}
<button onClick={() => removeFromCart(item)}>Remove</button>
</li>
))}
</ul>
<p>Total: ${total}</p>
</div>
<div className="product-list">
<h2>Available Products</h2>
<ul>
<li>
Product 1 - $10
<button onClick={() => addToCart({ name: 'Product 1', price: 10 })}>Add to Cart</button>
</li>
<li>
Product 2 - $20
<button onClick={() => addToCart({ name: 'Product 2', price: 20 })}>Add to Cart</button>
</li>
<li>
Product 3 - $30
<button onClick={() => addToCart({ name: 'Product 3', price: 30 })}>Add to Cart</button>
</li>
</ul>
</div>
</div>
);
};
export default CartPage;
In this example:
- We use React state to manage the
cartarray, which stores the items in the shopping cart, and thetotalvariable, which stores the total price of the items in the cart. - The
addToCartfunction adds an item to the cart by creating a new array with the item and updating the state. - The
removeFromCartfunction removes an item from the cart by filtering out the item to be removed and updating the state. - The
calculateTotalfunction calculates the total price of the items in the cart and updates thetotalstate. - The component renders the cart items and available products, allowing users to add and remove items from the cart.
This is a basic example of a shopping cart page in React. You can expand on this by adding more features like quantity adjustments, checkout functionality, and styling to make it more robust and user-friendly.







