Set Up Your React Project
Open your terminal and run the following commands:
npx create-react-app ecommerce-store
cd ecommerce-store
Step 2: Create the E-commerce Store Components
Replace the content of src/App.js
with the following code:
import React, { useState } from 'react';
import './App.css';
const productsData = [
{ id: 1, name: 'Product 1', price: 29.99, image: 'https://via.placeholder.com/150' },
{ id: 2, name: 'Product 2', price: 39.99, image: 'https://via.placeholder.com/150' },
{ id: 3, name: 'Product 3', price: 49.99, image: 'https://via.placeholder.com/150' },
];
const App = () => {
const [cart, setCart] = useState([]);
const addToCart = (product) => {
setCart([...cart, product]);
};
const getCartCount = () => {
return cart.length;
};
return (
<div className="App">
<header className="header">
<h1>E-commerce Store</h1>
<div className="cart">
<span>Cart: {getCartCount()} items</span>
</div>
</header>
<main>
<h2>Products</h2>
<div className="product-list">
{productsData.map((product) => (
<div key={product.id} className="product-card">
<img src={product.image} alt={product.name} />
<h3>{product.name}</h3>
<p>${product.price.toFixed(2)}</p>
<button onClick={() => addToCart(product)}>Add to Cart</button>
</div>
))}
</div>
</main>
<footer>
<p>© 2024 E-commerce Store</p>
</footer>
</div>
);
};
export default App;
Step 3: Style Your Store
Open src/App.css
and add the following styles:
body {
margin: 0;
font-family: Arial, sans-serif;
}
.App {
text-align: center;
padding: 20px;
}
.header {
background-color: #282c34;
color: white;
padding: 20px;
}
.header .cart {
margin-top: 10px;
}
.product-list {
display: flex;
justify-content: center;
flex-wrap: wrap;
}
.product-card {
border: 1px solid #ccc;
border-radius: 8px;
margin: 10px;
padding: 10px;
width: 200px;
text-align: center;
}
.product-card img {
width: 100%;
height: auto;
}
footer {
margin-top: 40px;
padding: 20px 0;
background-color: #f1f1f1;
}
Step 4: Run Your Application
In the terminal, run:
npm start
Leave a Reply