Code To Learn logo

Code To Learn

M6: State ManagementRedux Toolkit Path

L12: Update Router

Add the favorites route to enable navigation to the Favorites page

Now that we have the Navbar and FavoritesPage, let's connect them by adding the route!

Current Router Setup

Let's check our current Router configuration:

src/components/Router.jsx
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import HomePage from '@/pages/HomePage';
import ListingDetailsPage from '@/pages/ListingDetailsPage';
import NotFoundPage from '@/pages/NotFoundPage';

export function Router() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<HomePage />} />
        <Route path="/listings/:id" element={<ListingDetailsPage />} />
        <Route path="*" element={<NotFoundPage />} />
      </Routes>
    </BrowserRouter>
  );
}

Current routes:

  • / - HomePage
  • /listings/:id - ListingDetailsPage
  • * - NotFoundPage (catch-all)

We need to add /favorites!

Step 1: Import FavoritesPage

Add the import at the top:

src/components/Router.jsx
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import HomePage from '@/pages/HomePage';
import ListingDetailsPage from '@/pages/ListingDetailsPage';
import FavoritesPage from '@/pages/FavoritesPage';
import NotFoundPage from '@/pages/NotFoundPage';

export function Router() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<HomePage />} />
        <Route path="/listings/:id" element={<ListingDetailsPage />} />
        <Route path="*" element={<NotFoundPage />} />
      </Routes>
    </BrowserRouter>
  );
}

Step 2: Add Favorites Route

Add the new route before the catch-all route:

src/components/Router.jsx
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import HomePage from '@/pages/HomePage';
import ListingDetailsPage from '@/pages/ListingDetailsPage';
import FavoritesPage from '@/pages/FavoritesPage';
import NotFoundPage from '@/pages/NotFoundPage';

export function Router() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<HomePage />} />
        <Route path="/listings/:id" element={<ListingDetailsPage />} />
        <Route path="/favorites" element={<FavoritesPage />} />
        <Route path="*" element={<NotFoundPage />} />
      </Routes>
    </BrowserRouter>
  );
}

That's it! The favorites page is now accessible at /favorites! 🎉

Complete Router Code

Here's the complete updated Router:

src/components/Router.jsx
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import HomePage from '@/pages/HomePage';
import ListingDetailsPage from '@/pages/ListingDetailsPage';
import FavoritesPage from '@/pages/FavoritesPage';
import NotFoundPage from '@/pages/NotFoundPage';

export function Router() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<HomePage />} />
        <Route path="/listings/:id" element={<ListingDetailsPage />} />
        <Route path="/favorites" element={<FavoritesPage />} />
        <Route path="*" element={<NotFoundPage />} />
      </Routes>
    </BrowserRouter>
  );
}

Only 2 lines changed! Clean and simple. ✨

Understanding Route Order

The order of routes matters!

Route Patterns

Here are common route patterns:

Fixed URL paths:

<Route path="/" element={<HomePage />} />
<Route path="/about" element={<AboutPage />} />
<Route path="/contact" element={<ContactPage />} />
<Route path="/favorites" element={<FavoritesPage />} />

Matches exactly:

  • / → HomePage
  • /about → AboutPage
  • /contact → ContactPage
  • /favorites → FavoritesPage

Routes with parameters:

<Route path="/listings/:id" element={<ListingDetailsPage />} />
<Route path="/users/:userId" element={<UserProfile />} />
<Route path="/posts/:postId/comments/:commentId" element={<Comment />} />

Access params in component:

import { useParams } from 'react-router-dom';

function ListingDetailsPage() {
  const { id } = useParams();
  // If URL is /listings/123, id = "123"
}

Matches:

  • /listings/123 → id = "123"
  • /listings/abc → id = "abc"
  • /users/456 → userId = "456"

Routes inside routes:

<Route path="/dashboard" element={<DashboardLayout />}>
  <Route index element={<DashboardHome />} />
  <Route path="profile" element={<Profile />} />
  <Route path="settings" element={<Settings />} />
</Route>

DashboardLayout must include <Outlet />:

import { Outlet } from 'react-router-dom';

function DashboardLayout() {
  return (
    <div>
      <h1>Dashboard</h1>
      <Outlet />  {/* Child routes render here */}
    </div>
  );
}

Matches:

  • /dashboard → DashboardHome
  • /dashboard/profile → Profile
  • /dashboard/settings → Settings

Optional segments:

<Route path="/listings/:id?" element={<ListingsPage />} />

Matches both:

  • /listings → id = undefined
  • /listings/123 → id = "123"

Usage:

function ListingsPage() {
  const { id } = useParams();
  
  if (id) {
    // Show specific listing
  } else {
    // Show all listings
  }
}

Testing the Route

Let's verify the route works:

Click the "Favorites" link in the Navbar.

Expected:

  • URL changes to /favorites
  • FavoritesPage renders
  • Navbar stays visible

Check URL

Look at the browser address bar:

http://localhost:5173/favorites

The URL should show /favorites!

Refresh Page

Press F5 to refresh the page.

Expected:

  • Page reloads
  • Still shows FavoritesPage
  • URL is still /favorites

If this works, routing is configured correctly! ✅

Click "Home" in the Navbar.

Expected:

  • URL changes to /
  • HomePage renders
  • Smooth navigation (no page reload)

Complete Application Flow

Now the full navigation flow works:

HomePage (/)
  ↓ Click listing
ListingDetailsPage (/listings/:id)
  ↓ Click Favorites in Navbar
FavoritesPage (/favorites)
  ↓ Click Home in Navbar
HomePage (/)

All connected! 🎉

Route Visualization

Here's how all routes connect:

┌──────────────────────────────────────────┐
│           Navbar (always visible)        │
│  [StayScape]  [Home]  [Favorites (0)]   │
└──────────────────────────────────────────┘

┌──────────────────────────────────────────┐
│                 Routes                   │
│                                          │
│  /            → HomePage                 │
│  /listings/1  → ListingDetailsPage       │
│  /favorites   → FavoritesPage     │
│  /unknown     → NotFoundPage             │
│                                          │
└──────────────────────────────────────────┘

Common Router Issues

What's Next?

Perfect! The routing is complete. In the next lesson, we'll:

  1. Create Favorite Button - Heart icon toggle button
  2. Connect to Redux - Dispatch toggleFavorite action
  3. Show state - Filled/unfilled based on favorites

✅ Lesson Complete! The favorites route is now configured and navigation works!

Key Takeaways

  • Import page component before using in route
  • Add route with <Route path="/favorites" element={...} />
  • Route order matters - specific before general, * last
  • Test with refresh - Ensures routing configured correctly
  • Only 2 lines added - One import, one route
  • Client-side routing - No page reloads when navigating