reactshop-bazaar / src /App.jsx
Abanee's picture
create a e-commerce website using reactjs ,bootsrap
d39feec verified
Raw History Blame Contribute Delete
2.43 kB
import React, { useState, useEffect } from 'react'
import Header from './components/Header'
import ProductGrid from './components/ProductGrid'
import Cart from './components/Cart'
import './App.css'
function App() {
const [cart, setCart] = useState([])
const [showCart, setShowCart] = useState(false)
const [products, setProducts] = useState([])
useEffect(() => {
// Fetch products from Fake Store API
fetch('https://fakestoreapi.com/products')
.then(res => res.json())
.then(data => setProducts(data))
}, [])
const addToCart = (product) => {
setCart(prevCart => {
const existingItem = prevCart.find(item => item.id === product.id)
if (existingItem) {
return prevCart.map(item =>
item.id === product.id ? { ...item, quantity: item.quantity + 1 } : item
)
}
return [...prevCart, { ...product, quantity: 1 }]
})
}
const removeFromCart = (productId) => {
setCart(prevCart => prevCart.filter(item => item.id !== productId))
}
const updateQuantity = (productId, quantity) => {
if (quantity === 0) {
removeFromCart(productId)
} else {
setCart(prevCart =>
prevCart.map(item =>
item.id === productId ? { ...item, quantity } : item
)
}
}
}
const getTotalItems = () => {
return cart.reduce((total, item) => total + item.quantity, 0)
}
const getTotalPrice = () => {
return cart.reduce((total, item) => total + (item.price * item.quantity), 0)
}
return (
<div className="App">
<Header
cartItemsCount={getTotalItems()}
onCartClick={() => setShowCart(true)}
/>
<main className="container-fluid py-4">
<div className="row">
<div className="col-12">
<div className="text-center mb-5">
<h1 className="display-4 fw-bold text-primary">ReactShop Bazaar</h1>
<p className="lead text-muted">Your one-stop shop for everything amazing! 🛍️</p>
</div>
<ProductGrid products={products} onAddToCart={addToCart} />
</div>
</div>
</main>
<Cart
show={showCart}
onHide={() => setShowCart(false)}
cart={cart}
onUpdateQuantity={updateQuantity}
onRemoveFromCart={removeFromCart}
totalPrice={getTotalPrice()}
/>
</div>
)
}
export default App