JavaScript and React course Β· Module 6: React Router

Complete Routing Architecture - Navigation Command Center

5 min read Β·
In this lesson9

Navigator, we've reached the final stage of our journey through the Asteroid Belt! It's time to gather all the navigation techniques we've learned and build a complete routing system - a true Navigation Command Center for our cosmic fleet.

In this lesson, we'll see how all React Router elements work together in one cohesive application.

Architecture of a Complete Application with Routing

When building an application with full routing, we need to plan several layers:

  1. Authentication layer - AuthContext + ProtectedRoute
  2. Navigation layer - NavLink with active styles
  3. Routes layer - nested Routes with Outlet
  4. Parameters layer - dynamic paths with useParams
  5. Redirects layer - 404 handling and security

Folder Structure

In larger applications, it's worth organizing routing-related files in a logical structure:

src/
β”œβ”€β”€ App.jsx              // Main component with BrowserRouter
β”œβ”€β”€ routes/
β”‚   β”œβ”€β”€ AppRoutes.jsx    // Definition of all routes
β”‚   └── ProtectedRoute.jsx
β”œβ”€β”€ context/
β”‚   └── AuthContext.jsx  // Authentication context
β”œβ”€β”€ layouts/
β”‚   β”œβ”€β”€ MainLayout.jsx   // Layout with navigation and Outlet
β”‚   └── DashboardLayout.jsx
β”œβ”€β”€ pages/
β”‚   β”œβ”€β”€ HomePage.jsx
β”‚   β”œβ”€β”€ LoginPage.jsx
β”‚   β”œβ”€β”€ MissionDetail.jsx
β”‚   └── NotFound.jsx
└── components/
    └── Navigation.jsx   // NavLink menu

Such organization allows easy management of even extensive applications with dozens of routes.

Connecting AuthContext with Routing

The central element is the AuthProvider wrapping the entire application:

function AuthProvider({ children }) {
  const [user, setUser] = useState(null);

  const login = (name) => setUser({ name });
  const logout = () => setUser(null);

  return (
    <AuthContext.Provider value={{ user, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
}

// In App.jsx:
function App() {
  return (
    <AuthProvider>
      <BrowserRouter>
        <Navigation />
        <Routes>
          {/* public and protected routes */}
        </Routes>
      </BrowserRouter>
    </AuthProvider>
  );
}

The AuthProvider must be outside BrowserRouter so that the authentication context is available in all route components.

The navigation component combines NavLink (with active styles) with AuthContext (conditional display of options):

function Navigation() {
  const { user, logout } = useAuth();

  return (
    <nav>
      <NavLink to="/" className={({isActive}) => isActive ? 'active' : ''}>
        Home
      </NavLink>
      <NavLink to="/missions" className={({isActive}) => isActive ? 'active' : ''}>
        Missions
      </NavLink>

      {user ? (
        <>
          <NavLink to="/dashboard" className={({isActive}) => isActive ? 'active' : ''}>
            Dashboard
          </NavLink>
          <span>Logged in: {user.name}</span>
          <button onClick={logout}>Logout</button>
        </>
      ) : (
        <NavLink to="/login">Login</NavLink>
      )}
    </nav>
  );
}

This way the navigation automatically responds to the authentication state - a logged-in user sees the Dashboard and logout button, while an unauthenticated user sees the login link.

Nested Routes with Layout

The missions section uses nested routes with Outlet:

function MissionsLayout() {
  return (
    <div className="missions-layout">
      <aside>
        <h3>Missions</h3>
        <NavLink to="/missions/apollo">Apollo</NavLink>
        <NavLink to="/missions/artemis">Artemis</NavLink>
        <NavLink to="/missions/voyager">Voyager</NavLink>
      </aside>
      <main>
        <Outlet />
      </main>
    </div>
  );
}

// In route configuration:
<Route path="/missions" element={<MissionsLayout />}>
  <Route index element={<MissionsList />} />
  <Route path=":missionId" element={<MissionDetail />} />
</Route>

The index route (<Route index />) renders the default content (missions list) when the user is at /missions. The dynamic parameter :missionId handles specific mission details.

Complete Route Configuration

Here's what the full route configuration looks like combining all the techniques we've learned:

function App() {
  return (
    <AuthProvider>
      <BrowserRouter>
        <Navigation />
        <Routes>
          {/* Home page */}
          <Route path="/" element={<HomePage />} />

          {/* Login */}
          <Route path="/login" element={<LoginPage />} />

          {/* Nested routes with layout */}
          <Route path="/missions" element={<MissionsLayout />}>
            <Route index element={<MissionsList />} />
            <Route path=":missionId" element={<MissionDetail />} />
          </Route>

          {/* Protected route */}
          <Route path="/dashboard" element={
            <ProtectedRoute>
              <DashboardPage />
            </ProtectedRoute>
          } />

          {/* 404 handling */}
          <Route path="*" element={<NotFound />} />
        </Routes>
      </BrowserRouter>
    </AuthProvider>
  );
}

The order of elements matters:

  • Specific paths (/, /login, /missions) are matched first
  • The path="*" route must be last - it catches everything that doesn't match any defined route

Login with Path Remembering

The login page uses useNavigate and useLocation to redirect the user back to the page they were redirected from:

function LoginPage() {
  const [name, setName] = useState('');
  const { login } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();

  // Path the user was redirected from
  const from = location.state?.from?.pathname || '/dashboard';

  const handleSubmit = (e) => {
    e.preventDefault();
    if (name.trim()) {
      login(name);
      navigate(from, { replace: true }); // replace: true removes /login from history
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input value={name} onChange={(e) => setName(e.target.value)} />
      <button type="submit">Log In</button>
    </form>
  );
}

The replace: true option in navigate is crucial - thanks to it, the user won't return to the login page after clicking "Back" in the browser.

404 Page Handling

The Not Found page contains a link back to the home page:

function NotFound() {
  return (
    <div className="not-found">
      <h1>404</h1>
      <p>Page not found</p>
      <Link to="/">Return to home page</Link>
    </div>
  );
}

Architecture Summary

A complete application with routing in React combines the following elements:

ElementRoleHook / Component
Route containerEnables routingBrowserRouter
Route definitionMaps URLs to componentsRoutes, Route
NavigationLinks with active stylesNavLink
NestingShared layoutOutlet, Route children
Dynamic parametersElement detailsuseParams
Programmatic navigationRedirect after actionuseNavigate
Location statePassing hidden datauseLocation
Route protectionEnforcing loginProtectedRoute + Navigate
Error handlingNon-existent pagesRoute path="*"
Auth contextGlobal user datacreateContext + useContext

Try the complete application in the editor below - log in, navigate between missions, check the Dashboard, and test the 404 page!

Code for this lesson: App.jsx
import React, { useState, createContext, useContext, Suspense, lazy } from 'react';
import {
  BrowserRouter, Routes, Route, Link, NavLink,
  useParams, useNavigate, useLocation, Navigate, Outlet
} from 'react-router-dom';

// Auth Context
const AuthContext = createContext();
function useAuth() { return useContext(AuthContext); }

function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  const login = (name) => setUser({ name });
  const logout = () => setUser(null);
  return (
    <AuthContext.Provider value={{ user, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
}

// Protected Route
function ProtectedRoute({ children }) {
  const { user } = useAuth();
  const location = useLocation();
  if (!user) return <Navigate to="/login" state={{ from: location }} replace />;
  return children;
}

// Components
function Navigation() {
  const { user, logout } = useAuth();
  return (
    <nav>
      <div className="nav-brand">SpaceApp</div>
      <div className="nav-links">
        <NavLink to="/" className={({isActive}) => isActive ? 'active' : ''}>Home</NavLink>
        <NavLink to="/missions" className={({isActive}) => isActive ? 'active' : ''}>Missions</NavLink>
        {user ? (
          <>
            <NavLink to="/dashboard" className={({isActive}) => isActive ? 'active' : ''}>Dashboard</NavLink>
            <span className="user-badge">{user.name}</span>
            <button onClick={logout}>Logout</button>
          </>
        ) : (
          <NavLink to="/login" className={({isActive}) => isActive ? 'active' : ''}>Login</NavLink>
        )}
      </div>
    </nav>
  );
}

function HomePage() {
  return (
    <div className="page home">
      <h1>Welcome to SpaceApp</h1>
      <p>Your gateway to space exploration</p>
      <div className="features">
        <div className="feature">Track Missions</div>
        <div className="feature">View Analytics</div>
        <div className="feature">Manage Crew</div>
      </div>
    </div>
  );
}

function LoginPage() {
  const [name, setName] = useState('');
  const { login } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();
  const from = location.state?.from?.pathname || '/dashboard';

  const handleSubmit = (e) => {
    e.preventDefault();
    if (name.trim()) {
      login(name);
      navigate(from, { replace: true });
    }
  };

  return (
    <div className="page login">
      <h1>Login</h1>
      <form onSubmit={handleSubmit}>
        <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Username" />
        <button type="submit">Login</button>
      </form>
    </div>
  );
}

function MissionsLayout() {
  return (
    <div className="missions-layout">
      <aside>
        <h3>Missions</h3>
        <NavLink to="/missions/apollo">Apollo</NavLink>
        <NavLink to="/missions/artemis">Artemis</NavLink>
        <NavLink to="/missions/voyager">Voyager</NavLink>
      </aside>
      <main><Outlet /></main>
    </div>
  );
}

function MissionsList() {
  return <div className="content"><h2>Select a mission</h2></div>;
}

function MissionDetail() {
  const { missionId } = useParams();
  return (
    <div className="content">
      <h2>Mission: {missionId?.toUpperCase()}</h2>
      <p>Details for {missionId} mission</p>
    </div>
  );
}

function DashboardPage() {
  const { user } = useAuth();
  return (
    <div className="page dashboard">
      <h1>Dashboard</h1>
      <p>Welcome back, {user?.name}!</p>
      <div className="stats">
        <div className="stat"><span>Missions</span>12</div>
        <div className="stat"><span>Crew</span>48</div>
        <div className="stat"><span>Ships</span>8</div>
      </div>
    </div>
  );
}

function NotFound() {
  return (
    <div className="page not-found">
      <h1>404</h1>
      <p>Page not found</p>
      <Link to="/">Go Home</Link>
    </div>
  );
}

function App() {
  return (
    <AuthProvider>
      <BrowserRouter>
        <div className="app">
          <Navigation />
          <Routes>
            <Route path="/" element={<HomePage />} />
            <Route path="/login" element={<LoginPage />} />
            <Route path="/missions" element={<MissionsLayout />}>
              <Route index element={<MissionsList />} />
              <Route path=":missionId" element={<MissionDetail />} />
            </Route>
            <Route path="/dashboard" element={
              <ProtectedRoute><DashboardPage /></ProtectedRoute>
            } />
            <Route path="*" element={<NotFound />} />
          </Routes>
        </div>
      </BrowserRouter>
    </AuthProvider>
  );
}

export default App;

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. How do you implement a Protected Route in React Router?

  2. 2. Where in the parent component do you place <Outlet /> to render nested routes?

These are 2 of 7 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Implement 404 error handling with Route path='*' and a NotFound component. Add navigation with links to existing and non-existent pages to test the error handling.

  • Click in order

    Arrange the programmatic navigation with state:

  • Vertical ordering

    Arrange the steps for programmatic navigation using useNavigate:

  • Vertical ordering

    Arrange the steps for passing and reading data between routes:

  • Vertical ordering

    Arrange the steps for implementing a Protected Route with the Navigate component:

  • Click in order

    Arrange the search params management:

  • Vertical ordering

    Arrange the navigation steps in React Router from clicking a link to displaying the page:

  • Vertical ordering

    Arrange the steps for handling unauthorized access to a protected route:

  • Horizontal ordering

    Arrange the elements of a route handling the 404 page:

  • Horizontal ordering

    Arrange the Route syntax with a dynamic id parameter:

  • Code editor

    Build a comprehensive Navigation System including: React Router setup with BrowserRouter, nested routes for the /fleet/:id/missions/:missionId structure, dynamic routing with params, Link and NavLink components with active styles, useNavigate for programmatic navigation, useParams and useLocation hooks, protected routes with authentication, lazy loading with React.lazy and Suspense, search params with useSearchParams, and 404 error handling. Create a navigation system worthy of the most advanced fleet traversing the Asteroid Belt!

  1. QuestionProtected Routes
  2. Coding taskPractice: Routing exercise
  3. Click in orderProgrammatic navigation
  4. Put in orderProgrammatic navigation in React Router
  5. Put in orderPassing data through location state
  6. QuestionOutlet component in nested routes
  7. QuestionError handling in routing
  8. Put in orderNavigate component for redirects
  9. Click in orderManaging search parameters
  10. Put in orderNavigation process in React Router
  11. Put in orderAuthorization flow in ProtectedRoute
  12. Put in orderHandling the 404 page in React Router
  13. QuestionTesting components with routing
  14. QuestionPassing state through navigation
  15. Put in orderRoute definition with a parameter
  16. QuestionIndex Route in React Router
  17. QuestionLazy loading routes in React Router
  18. Coding taskProject: Navigation System
  19. Project to submitMentor project: Galactic Navigation Center
  20. VideoVideo: Module Summary

Useful articles