Part 84: Building an Add-to-Cart Feature for Your Product Page
[Pages] Shopping Cart (Exercises)

Creating an engaging and user-friendly shopping experience is essential for any e-commerce platform. One of the key features is allowing customers to add products to their cart directly from the product page. In this post, we'll walk through creating a user interface that enables this functionality, complete with a quantity selector and an "Add to Cart" button.
Step 1: Designing the User Interface
To facilitate adding products to the cart, we need a straightforward interface on each product page. This will include an input for the quantity and a button for adding the product to the cart.
Creating a Separate Component
Let's create a dedicated React component for this functionality, which we'll call AddToCartWidget. This component will handle the quantity input and the add-to-cart action.
// File: components/AddToCartWidget.js
const { useState } = require('react');
import Button from './Button';
function AddToCartWidget({ productId }) {
const [quantity, setQuantity] = useState(1);
const handleClick = async () => {
console.log('should add to cart:', { productId, quantity });
};
return (
<div className="py-2">
<input type="number" min="1"
className="border rounded px-3 py-1 mr-2 w-16 text-right"
value={quantity.toString()}
onChange={(event) => setQuantity(parseInt(event.target.value))}
/>
<Button onClick={handleClick}>
Add to cart
</Button>
</div>
);
}
export default AddToCartWidget;Explanation
State Management: We use the
useStatehook to manage the quantity state. It initializes at 1, allowing users to adjust the quantity.Input Field: The input field of type
numberlets users specify how many units they want. We ensure the value is always converted between string and number formats to maintain consistency.Button Component: The
Buttoncomponent is used for the "Add to Cart" action. When clicked, it logs theproductIdandquantityto the console.
Step 2: Integrating the Component into the Product Page
Now, we need to integrate our AddToCartWidget into the existing product page, ensuring it's only visible to signed-in users.
// File: pages/products/[id].js
import Image from 'next/image';
import AddToCartWidget from '../../components/AddToCartWidget';
import Page from '../../components/Page';
import { useUser } from '../../hooks/user';
import { ApiError } from '../../lib/api';
import { getProduct, getProducts } from '../../lib/products';
export async function getStaticProps({ params: { id } }) {
// Fetch product details logic
}
function ProductPage({ product }) {
const user = useUser();
console.log('[ProductPage] render:', product);
return (
<Page title={product.title}>
<div className="product-details">
<Image src={product.image} alt={product.title} width={500} height={500} />
<div className="product-info">
<h1>{product.title}</h1>
<p className="text-lg font-bold mt-2">
{product.price}
</p>
{user && <AddToCartWidget productId={product.id} />}
</div>
</div>
</Page>
);
}
export default ProductPage;Explanation
User Authentication: We utilize a custom
useUserhook to determine if a user is signed in. TheAddToCartWidgetis only displayed ifuseris present.Passing Props: The
productIdis passed as a prop to theAddToCartWidget, allowing it to identify which product to add to the cart.
Conclusion
By following these steps, we've successfully created a user interface that allows customers to select a quantity and prepare to add a product to their cart. Although the current implementation only logs the action to the console, it sets a solid foundation for integrating actual API requests in future steps. This feature enhances the shopping experience, making it easier for users to interact with your store. Stay tuned for the next part, where we'll handle the API integration for adding items to the cart.
Last updated