Shopping Chart Reactjs

Creating a shopping cart in a React.js application using TypeScript involves managing state, handling user interactions, and updating the cart dynamically. Below is an example of how you can implement a simple shopping cart:
Step 1: Define Types
Start by defining the types for your products and cart items.
typescript
// types.ts
export interface Product {
id: number;
name: string;
price: number;
}
export interface CartItem extends Product {
quantity: number;
}Step 2: Create the Shopping Cart Component
Create a ShoppingCart component that manages the state of the cart.
typescript
// components/ShoppingCart.tsx
import React, { useState } from 'react';
import { Product, CartItem } from '../types';
interface ShoppingCartProps {
products: Product[];
}
const ShoppingCart: React.FC<ShoppingCartProps> = ({ products }) => {
const [cartItems, setCartItems] = useState<CartItem[]>([]);
const addToCart = (product: Product) => {
setCartItems(prevItems => {
const itemExists = prevItems.find(item => item.id === product.id);
if (itemExists) {
return prevItems.map(item =>
item.id === product.id ? { ...item, quantity: item.quantity + 1 } : item
);
}
return [...prevItems, { ...product, quantity: 1 }];
});
};
const removeFromCart = (productId: number) => {
setCartItems(prevItems =>
prevItems
.map(item => (item.id === productId ? { ...item, quantity: item.quantity - 1 } : item))
.filter(item => item.quantity > 0)
);
};
const getTotalPrice = () => {
return cartItems.reduce((total, item) => total + item.price * item.quantity, 0);
};
return (
<div>
<h2>Products</h2>
<ul>
{products.map(product => (
<li key={product.id}>
{product.name} - ${product.price.toFixed(2)}
<button onClick={() => addToCart(product)}>Add to Cart</button>
</li>
))}
</ul>
<h2>Shopping Cart</h2>
{cartItems.length === 0 ? (
<p>Your cart is empty</p>
) : (
<ul>
{cartItems.map(item => (
<li key={item.id}>
{item.name} - ${item.price.toFixed(2)} x {item.quantity}
<button onClick={() => removeFromCart(item.id)}>Remove</button>
</li>
))}
</ul>
)}
<h3>Total: ${getTotalPrice().toFixed(2)}</h3>
</div>
);
};
export default ShoppingCart;
Step 3: Use the Shopping Cart Component
Now, use the ShoppingCart component in your main application file and pass in some sample products.
typescript
// pages/index.tsx
import React from 'react';
import ShoppingCart from '../components/ShoppingCart';
import { Product } from '../types';
const products: Product[] = [
{ id: 1, name: 'Apple', price: 0.99 },
{ id: 2, name: 'Banana', price: 0.79 },
{ id: 3, name: 'Orange', price: 0.89 },
];
const Home: React.FC = () => {
return (
<div>
<h1>Shopping Cart Example</h1>
<ShoppingCart products={products} />
</div>
);
};
export default Home;
Step 4: Styling (Optional)
You can add some basic styling using CSS or Tailwind CSS. Here's an example using plain CSS:
typescript
/* styles.css */
ul {
list-style-type: none;
padding: 0;
}
li {
margin: 10px 0;
}
button {
margin-left: 10px;
padding: 5px 10px;
background-color: #007bff;
color: white;
border: none;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
Step 5: Integrate the Styling
Import the CSS file into your project:
typescript
// pages/_app.tsx
import '../styles.css';
import type { AppProps } from 'next/app';
export default function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />;
}
Step 6: Running the Project
Ensure that your Next.js project is set up correctly with TypeScript:
typescript
npx create-next-app@latest my-shopping-cart --typescript
cd my-shopping-cart
Then, run your project:
bash
npm run dev