Part 79: Creating a Shopping Cart Page with Navigation in React
[Pages] Shopping Cart (Exercises)

In our journey to enhance user experience in our web application, the next step is to add a shopping cart page. This page will display the items users have added to their cart. In this post, we'll walk through the process of creating a new cart page and linking it to our navigation bar, ensuring it's only accessible to authenticated users.
Setting Up the Cart Page
First, let's create a new page for the cart. This will be a simple React component that we'll expand in later steps to display cart items.
Creating the Cart Page Component
To start, create a new file named cart.js in the pages directory of your project. This will be our cart page component.
// File: pages/cart.js
import Page from '../components/Page';
function CartPage() {
return (
<Page title="Cart">
<h1>Cart</h1>
</Page>
);
}
export default CartPage;In this component, we're using a shared Page component to ensure consistent styling and layout across our application. The CartPage component currently just displays a title, "Cart". We'll add functionality to display cart items in future steps.
Adding Navigation to the Cart Page
Now that we have our cart page set up, the next step is to add a link to it in our navigation bar. This link should only be visible to authenticated users, as the cart is user-specific.
Modifying the NavBar Component
Locate your NavBar component file, typically found in the components directory. We'll add a link to the cart page here.
// File: components/NavBar.js
import Link from 'next/link';
import { useContext } from 'react';
import { UserContext } from '../context/UserContext';
function NavBar() {
const { user } = useContext(UserContext);
return (
<nav>
<ul>
<li>
<Link href="/">Home</Link>
</li>
{/* Conditional rendering based on user authentication */}
{user && (
<>
<li>
<Link href="/cart">Cart</Link>
</li>
<li>
{user.name}
</li>
</>
)}
<li role="separator" className="flex-1" />
</ul>
</nav>
);
}
export default NavBar;In this code, we're using React's useContext hook to access the UserContext, which provides user information. The cart link is conditionally rendered, only appearing if a user is signed in. This ensures that only authenticated users can access their cart.
Conclusion
With these changes, your application now has a "Cart" page accessible via the navigation bar, but only for logged-in users. This setup helps reinforce the concept of user-specific functionality and secure access to personal data. In upcoming steps, we'll focus on populating the cart page with actual cart items retrieved from our backend API, providing users with a comprehensive view of their shopping cart.
Feel free to experiment and expand on these basics. As you continue to build out your application, consider how you can further enhance the user experience by integrating additional features and refining existing ones.
Last updated