In modern e-commerce applications, the "Order History" page is a vital touchpoint. It requires a blend of authentication logic, asynchronous data fetching, and clean UI presentation.
Below is an article-style breakdown of how to build a robust "My Orders" component using React and React Router.
- Setting the Foundation
Every React component begins with its imports. Here, we bring in the necessary hooks for state and side effects, as well as useNavigate for handling user redirection.
JavaScript
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import './MyOrders.css'
function MyOrders({ user }) {
const navigate = useNavigate()
const [orders, setOrders] = useState([])
- Implementing the Security Guard
We don't want unauthorized users accessing order data. We use the useEffect hook to check if a user exists. If not, we programmatically move them to the login page before any data is requested.
JavaScript
useEffect(() => {
if (!user) {
navigate('/login')
return
}
const load = async () => {
const res = await fetch(`/api/orders/${user.customerID}`)
const data = await res.json()
setOrders(data)
}
load()
}, [user])
- Handling the "Loading" or "Unauthorized" State
Even though we redirect in the background, we need a "fallback" UI to prevent the component from trying to render properties of a null user, which would crash the app.
JavaScript
if (!user) return
Please log in.
- The Presentation Layer
Once the data is fetched, we use the .map() function to iterate through the orders array. We also include a "Conditional Rendering" check to show a friendly message if the user hasn't bought anything yet.
JavaScript
return (
My Orders
{orders.length === 0 &&
No orders yet.
}{orders.map(order => (
{order.product_name}
Quantity: {order.product_quantity}
Date: {new Date(order.order_date).toLocaleDateString()}
))}
)
}
export default MyOrders
- Styling for Readability
Clean code deserves a clean interface. The CSS focuses on "scannability"—making it easy for the user to distinguish between different orders at a glance using cards and specific color accents.
CSS
.page {
padding: 30px;
}
.order-card {
border: 1px solid #ccc;
border-radius: 8px;
padding: 16px;
margin-bottom: 10px;
max-width: 500px;
}
.order-product {
font-weight: 700;
margin-bottom: 8px;
color: #144A5C; /* A professional slate-blue for product titles */
}
Summary of Techniques Used
Redirect Logic: Utilizing useNavigate to protect private routes.
Data Hydration: Fetching user-specific data via customerID.
User Experience: Formatting raw ISO dates into localized, readable strings (e.g., "1/12/2024").
Scalability: Using key props on mapped elements to ensure React manages the list efficiently.
Top comments (0)