Lesson 10 of 10
Practice & Quiz - React Router v6
Test your knowledge of React Router v6: nested routes, protected routes, useNavigate, dynamic params, and loaders with a practical auth-guard exercise and 5 quiz questions.
Practical Exercise - Protected Route with Auth Guard
Practical Exercise - Protected Route with Auth Guard
import { createBrowserRouter, RouterProvider, Navigate, Outlet, useNavigate, useParams } from 'react-router-dom';
import { useState } from 'react';
// ─── Auth context (minimal) ────────────────────────────────────
const fakeUser = { id: 1, name: 'Alice', role: 'admin' };
// ─── Protected Route - wraps any route needing auth ────────────
function ProtectedRoute({ allowedRoles }: { allowedRoles?: string[] }) {
const isAuthenticated = !!localStorage.getItem('token');
const userRole = fakeUser.role;
if (!isAuthenticated) {
// Redirect to login, saving current location for redirect-back
return <Navigate to="/login" replace />;
}
if (allowedRoles && !allowedRoles.includes(userRole)) {
return <Navigate to="/unauthorized" replace />;
}
// Renders the matched child route
return <Outlet />;
}
// ─── Layout with nested outlet ─────────────────────────────────
function DashboardLayout() {
const navigate = useNavigate();
return (
<div>
<nav>
<button onClick={() => navigate('/dashboard/profile')}>Profile</button>
<button onClick={() => navigate('/dashboard/settings')}>Settings</button>
<button onClick={() => { localStorage.removeItem('token'); navigate('/login'); }}>
Logout
</button>
</nav>
<main><Outlet /></main>
</div>
);
}
function UserProfile() {
const { userId } = useParams<{ userId: string }>();
return <h2>Profile for user: {userId ?? fakeUser.name}</h2>;
}
// ─── Router definition ─────────────────────────────────────────
const router = createBrowserRouter([
{ path: '/login', element: <div>Login Page</div> },
{ path: '/unauthorized', element: <div>403 Forbidden</div> },
{
path: '/dashboard',
element: <ProtectedRoute />, // gate for all dashboard routes
children: [
{
element: <DashboardLayout />, // nested layout
children: [
{ index: true, element: <h2>Dashboard Home</h2> },
{ path: 'profile', element: <UserProfile /> },
{ path: 'profile/:userId', element: <UserProfile /> },
{
path: 'settings',
element: <ProtectedRoute allowedRoles={['admin']} />,
children: [{ index: true, element: <h2>Admin Settings</h2> }],
},
],
},
],
},
{ path: '*', element: <Navigate to="/dashboard" replace /> },
]);
export default function App() {
return <RouterProvider router={router} />;
}Diagram
Loading diagram…
Modern React: Use Hooks instead of class lifecycle methods
Module Quiz
Module Quiz
Question 1 of 5What is the purpose of the `<Outlet />` component in React Router v6?
Finished this lesson?
0 of 10 in Module 3