Weβll create:
App
: Main component
ProductList
: Shows a list of products
ProductItem
: One single product
Cart
: Shows added items
- Use props to pass data, and hooks like
useState
and useEffect
π§± 1. App.js
β Main Component
import React, { useState } from "react";
import ProductList from "./ProductList";
import Cart from "./Cart";
function App() {
const [cartItems, setCartItems] = useState([]);
const handleAddToCart = (product) => {
setCartItems((prevItems) => [...prevItems, product]);
};
return (
<div>
<h1>πΆ Pet Store</h1>
<ProductList onAddToCart={handleAddToCart} />
<Cart items={cartItems} />
</div>
);
}
export default App;
β
What you learned:
cartItems
is state (useState
)
- We pass the function
handleAddToCart
as a prop to child
- We pass data
cartItems
to Cart
as a prop
π 2. ProductList.js
β List of Products
import React from "react";
import ProductItem from "./ProductItem";
const products = [
{ id: 1, name: "Cat Toy", price: 10 },
{ id: 2, name: "Dog Food", price: 25 },
{ id: 3, name: "Bird Cage", price: 40 }
];
function ProductList({ onAddToCart }) {
return (
<div>
<h2>π Products</h2>
{products.map((product) => (
<ProductItem key={product.id} product={product} onAddToCart={onAddToCart} />
))}
</div>
);
}
export default ProductList;
β
What you learned:
- We pass
product
and onAddToCart
as props to ProductItem
π§Έ 3. ProductItem.js
β One Product
import React from "react";
function ProductItem({ product, onAddToCart }) {
return (
<div style={{ border: "1px solid gray", padding: "10px", margin: "5px" }}>
<h3>{product.name}</h3>
<p>Price: ${product.price}</p>
<button onClick={() => onAddToCart(product)}>Add to Cart</button>
</div>
);
}
export default ProductItem;
β
What you learned:
product
is a prop (an object with name & price)
- We call
onAddToCart(product)
when clicking the button
π 4. Cart.js
β Shopping Cart Component
import React, { useEffect } from "react";
function Cart({ items }) {
useEffect(() => {
console.log("π Cart updated!", items);
}, [items]); // π Watch the `items` change
return (
<div>
<h2>π Cart</h2>
{items.length === 0 && <p>No items in cart.</p>}
<ul>
{items.map((item, index) => (
<li key={index}>{item.name} - ${item.price}</li>
))}
</ul>
</div>
);
}
export default Cart;
β
What you learned:
useEffect(() => {}, [items])
: Runs only when items change
- Great for doing something like logging, fetching data, or analytics
π Hooks Used
Hook | Why we use it |
---|
useState | To manage the cartβs state |
useEffect | To react to changes in cart items |
π Summary
Concept | Example |
---|
Props | product , onAddToCart , items |
Pass function | Pass handleAddToCart from parent to child |
useState | Store the cart items |
useEffect | Run something when data (like items ) changes |
Multiple components | App, ProductList, ProductItem, Cart |
Comments are closed.