Creating a Simple E-Commerce Website with Next.js


Introduction

Building an e-commerce website is a comprehensive endeavor, but we'll provide an overview of creating a simple e-commerce site using Next.js. We'll cover project setup, product listings, and a basic shopping cart. In a real-world scenario, you'd need additional features like user authentication, payment processing, and a database for managing products and orders.


Setting Up the Project

Ensure you have Node.js and npm installed on your system. If not, download and install them from the official website.


Create a new Next.js project using the following commands:


        npx create-next-app e-commerce-website
cd e-commerce-website

Creating Product Listings

We'll start by creating a simple product listing page. We'll use a JSON file to represent products for this example.


        <!-- pages/products.js -->
import React from 'react';
const products = [
{
id: 1,
name: 'Product 1',
price: 10.99,
image: '/product1.jpg',
},
{
id: 2,
name: 'Product 2',
price: 15.99,
image: '/product2.jpg',
},
// Add more products
];
export default function Products() {
return (
<div>
<h2>Products</h2>
<div className="product-list">
{products.map((product) => (
<div key={product.id} className="product">
<img src={product.image} alt={product.name} />
<h3>{product.name}</h3>
<p>${product.price.toFixed(2)}</p>
<button>Add to Cart</button>
</div>
))}
</div>
</div>
);
}

Creating a Simple Shopping Cart

We'll create a basic shopping cart to add and remove items. In a real e-commerce project, you'd use more advanced cart management and possibly integrate with a state management library like Redux.


        <!-- pages/cart.js -->
import React, { useState } from 'react';
export default function Cart() {
const [cart, setCart] = useState([]);
const [total, setTotal] = useState(0);
const addToCart = (product) => {
const updatedCart = [...cart, product];
setCart(updatedCart);
const updatedTotal = total + product.price;
setTotal(updatedTotal);
};
const removeFromCart = (productId) => {
const updatedCart = cart.filter((product) => product.id !== productId);
setCart(updatedCart);
const updatedTotal = updatedCart.reduce((sum, product) => sum + product.price, 0);
setTotal(updatedTotal);
};
return (
<div>
<h2>Shopping Cart</h2>
<div className="cart">
{cart.map((product) => (
<div key={product.id} className="cart-item">
<h3>{product.name}</h3>
<p>${product.price.toFixed(2)}</p>
<button onClick={() => removeFromCart(product.id)}>Remove</button>
</div>
))}
</div>
<p>Total: ${total.toFixed(2)}</p>
</div>
);
}

Conclusion

You've learned how to create a basic e-commerce website with Next.js, including project setup, product listings, and a simple shopping cart. In a real-world e-commerce project, you would need additional features like user authentication, payment processing, and a database for managing products and orders. You can customize and expand this foundation based on your specific e-commerce needs.