Static Routing with React Router 7
Lecture
Section titled “Lecture”Our resource directory now loads data and remembers a selection. Let’s give the application a second screen for managing those resources. We want a URL for each screen, navigation between them, and a header that stays in place.
We’ll use React Router 7 in its declarative mode. The routes will have fixed paths: / for the directory and /admin for management. Here, static routing means those fixed path patterns; the pages can still fetch and change data.
Learning Outcome Guide
Section titled “Learning Outcome Guide”At the end of this class, you should be able to…
- Configure
BrowserRouter,Routes, andRoutefor fixed client-side paths. - Move existing functionality into a page component without losing its behaviour.
- Use a layout route and
Outletto share the header and page layout. - Use
NavLinkto navigate and identify the active page. - Build a basic create-resource form with pending, success, and error feedback.
Plan the responsibilities
Section titled “Plan the responsibilities”| File | Responsibility after the refactor |
|---|---|
main.jsx |
Defines the router and route tree |
App.jsx |
Renders the shared layout and an Outlet |
Header.jsx |
Contains navigation to both pages |
ResourceDirectoryPage.jsx |
Owns directory filters, selection, fetching, and composition |
AdminPage.jsx |
Loads the management list and handles the create form |
PageLayout.jsx |
Continues to supply the responsive grid |
The nested route’s element appears where App renders Outlet. The index route supplies the default child at /. React Router’s routing guide shows this relationship.
Our resource ids will still be used in API requests, but we won’t introduce route parameters, loaders, or actions in this lesson.
What navigation preserves
Section titled “What navigation preserves”The shared layout stays mounted when we move between its child routes. The page component being left is removed, and the page being entered mounts. Returning to the directory creates fresh filter state and fetches the list again. Selection can be restored from sessionStorage through our custom hook.
Calling useResources in both pages gives each page its own request state. The hook doesn’t create a shared cache.
Activity
Section titled “Activity”Starter Kit Code
Section titled “Starter Kit Code”From the root of your workbook, grab today’s starter for your section, or continue with your existing copy.
pnpm dlx tiged --disable-cache --force DG-InClass/SDEV-2150-A01-Sep-2026/sk/day-17/example/lesson-17-starter ./src/lesson-17pnpm dlx tiged --disable-cache --force DG-InClass/SDEV-2150-A02-Sep-2026/sk/day-17/example/lesson-17-starter ./src/lesson-17Use two terminals, each starting at the workbook root.
cd src/lesson-17/frontendpnpm installpnpm add react-router@7pnpm devcd src/lesson-17/backendpnpm installpnpm startUse the frontend URL printed by Vite, and check that the backend resource list is available. Install react-router in the frontend, following the package used in the declarative installation guide.
Code Walkthrough
Section titled “Code Walkthrough”Paths below start inside src/lesson-17/frontend.
-
Check the existing directory and request cleanup.
Select a resource and refresh. Confirm that the backend list loads and selection returns.
The supplied starter’s
src/hooks/useResources.jscontains the earlier demonstration implementation, including a two-second delay. Before adding navigation, replace that file with the completeuseResources.jsfrom Lesson 16’s Code Walkthrough, in the step Create a hook for loading resources. If you’re continuing your completed Lesson 16 code, keep that version.Check that it uses
requestVersionto retry, creates its controller inside the Effect, and guards completion updates withsignal.aborted. Its returned values are stillresources,isLoading,error, andrefetch.This prepares us for leaving a page while its request is pending. Refresh once more to confirm the directory still loads.
-
Move the directory into a page component.
Create
src/pages. Copy the entire currentsrc/App.jsxintosrc/pages/ResourceDirectoryPage.jsx. We’ll edit that copy first; leave the original App in place for the moment.In the copied file, combine the React imports, fix relative paths, and remove the layout imports.
src/pages/ResourceDirectoryPage.jsx import { useState } from 'react';import { useResources } from './hooks/useResources';import { useSelectedResource } from './hooks/useSelectedResource';import { useEffect, useState } from 'react';import { useResources } from '../hooks/useResources';import { useSelectedResource } from '../hooks/useSelectedResource';import Header from './components/Header';import Filters from './components/Filters';import Results from './components/Results';import Details from './components/Details';import PageLayout from './components/layout/PageLayout';import { useEffect } from 'react';import Filters from '../components/Filters';import Results from '../components/Results';import Details from '../components/Details';function App() {function ResourceDirectoryPage() {Keep the state, hooks, existing selection-logging Effect, and all three directory sections. Change only the outside layout tags to a fragment, and rename the export at the bottom.
src/pages/ResourceDirectoryPage.jsx return (<PageLayout header={<Header tagline="Find the right resources, right away" />}><>src/pages/ResourceDirectoryPage.jsx </PageLayout></>);}export default App;export default ResourceDirectoryPage;The starter’s loading and error messages also need to span the shared grid. Find these two elements in the copied page.
src/pages/ResourceDirectoryPage.jsx {isLoading && (<div className="text-sm text-base-content/70">Loading resources...</div><div role="status" className="md:col-span-3 text-sm text-base-content/70">Loading resources...</div>)}{error && (<div className="alert alert-error"><div role="alert" className="md:col-span-3 alert alert-error">If you continued from Lesson 16, your messages are already inside the Results column; keep that arrangement instead.
A fragment adds no wrapper element to the DOM. Our Filters, Results, and Details wrappers can therefore remain direct children of PageLayout’s grid.
-
Create the second page with a live resource list.
Add a new
src/pages/AdminPage.jsxfile. This small page uses the existing Card and fetching hook.src/pages/AdminPage.jsx import Card from '../components/ui/Card';import { useResources } from '../hooks/useResources';export default function AdminPage() {const { resources, isLoading, error, refetch } = useResources();return (<div className="md:col-span-3 space-y-4"><div><h2 className="text-2xl font-bold">Manage resources</h2><p>Create a resource and check the current list.</p></div>{isLoading ? (<p role="status">Loading resources...</p>) : error ? (<div role="alert" className="alert alert-error"><span>{error.message}</span><button type="button" className="btn btn-sm" onClick={refetch}>Try again</button></div>) : (<Card title={`Current resources (${resources.length})`}><ul className="space-y-2 p-4">{resources.map((resource) => (<li key={resource.id} className="rounded border border-base-300 p-3"><p className="font-semibold">{resource.title}</p><p className="text-sm">{resource.category}</p></li>))}</ul>{resources.length === 0 && <p className="p-4">No resources yet.</p>}</Card>)}</div>);}The outer
md:col-span-3wrapper lets this page occupy the full grid width. Our directory uses three grid children; Admin uses one full-width child. -
Turn App into the shared layout.
Our directory code is now in its own file. Replace
src/App.jsxwith this small layout component. The full file is shown because its responsibility has changed completely.src/App.jsx import { Outlet } from 'react-router';import Header from './components/Header';import PageLayout from './components/layout/PageLayout';export default function App() {return (<PageLayout header={<Header tagline="Find the right resources, right away" />}><Outlet /></PageLayout>);}Wire the route tree in
src/main.jsxbefore checking the browser. Until the child routes are configured, the outlet has no page to display.src/main.jsx import { StrictMode } from 'react';import { createRoot } from 'react-dom/client';import { BrowserRouter, Routes, Route } from 'react-router';import './index.css';import App from './App.jsx';import ResourceDirectoryPage from './pages/ResourceDirectoryPage';import AdminPage from './pages/AdminPage';createRoot(document.getElementById('root')).render(<StrictMode><App /><BrowserRouter><Routes><Route path="/" element={<App />}><Route index element={<ResourceDirectoryPage />} /><Route path="admin" element={<AdminPage />} /></Route></Routes></BrowserRouter></StrictMode>,);Visit
/on your frontend’s origin. The directory should work again. Now enter/adminin the address bar: the management list should appear beneath the same header. Keep the API’s port 3000 separate from the frontend URL. -
Add shared navigation.
In Header, import
NavLinkand add a<nav>after the title/tagline group.src/components/Header.jsx import { NavLink } from 'react-router';// src/components/Header.jsxexport default function Header({ tagline }) {src/components/Header.jsx {tagline ? tagline : 'Find student support services, labs, and campus resources.'}</p></div><nav aria-label="Main navigation" className="flex gap-2"><NavLink to="/" endclassName={({ isActive }) => `btn btn-sm ${isActive ? 'btn-primary' : 'btn-ghost'}`}>Directory</NavLink><NavLink to="/admin"className={({ isActive }) => `btn btn-sm ${isActive ? 'btn-primary' : 'btn-ghost'}`}>Admin</NavLink></nav></div>Move between pages using the links, then use the browser’s Back and Forward buttons. The URL and highlighted link should agree.
NavLinksuppliesisActivefor styling and marks the current page for assistive technology.Select a resource, visit Admin, then return to Directory. The selection should restore, while the filters return to their initial values. Explain that result using page mounting and session storage.
-
Prepare a small create-resource form.
In AdminPage, import
useStateand define the initial values outside the component.src/pages/AdminPage.jsx import { useState } from 'react';import Card from '../components/ui/Card';import { useResources } from '../hooks/useResources';const initialForm = {title: '',category: 'Academic',summary: 'A student support resource.',location: 'NAIT Campus',hours: 'Contact for hours',contact: 'support@example.com',virtual: false,openNow: false,};export default function AdminPage() {const { resources, isLoading, error, refetch } = useResources();const [formData, setFormData] = useState(initialForm);const [isSaving, setIsSaving] = useState(false);const [saveError, setSaveError] = useState('');const [saveMessage, setSaveMessage] = useState('');The backend requires all eight fields, with booleans for
virtualandopenNow. We’ll edit the title in class and send the shown demonstration defaults for the other fields. Completing those controls is part of Practice. The backend generates the id for a new resource.Insert the form between the page introduction and the loading/list conditional.
src/pages/AdminPage.jsx <p>Create a resource and check the current list.</p></div><Card title="New resource"><form onSubmit={handleCreateResource} className="space-y-3 p-4"><p className="text-sm">Enter a title. The other fields use our demonstration defaults.</p><label htmlFor="resource-title" className="block font-semibold">Resource title</label><input id="resource-title" className="input w-full" requiredvalue={formData.title} disabled={isSaving}onChange={(e) => setFormData({ ...formData, title: e.target.value })} /><button type="submit" className="btn btn-primary" disabled={isSaving}>{isSaving ? 'Saving...' : 'Add resource'}</button>{saveError && <p role="alert" className="text-error">{saveError}</p>}<p role="status">{saveMessage}</p></form></Card>{isLoading ? (Add the handler in the next step before testing this form.
-
Create a resource and handle the response.
Put this handler after the state declarations and before AdminPage’s return.
src/pages/AdminPage.jsx const [saveMessage, setSaveMessage] = useState('');async function handleCreateResource(e) {e.preventDefault();if (isSaving) return;setSaveError('');setSaveMessage('');if (!formData.title.trim()) {setSaveError('Enter a resource title.');return;}setIsSaving(true);try {const response = await fetch('http://localhost:3000/resources', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ ...formData, title: formData.title.trim() }),});if (!response.ok) {throw new Error(`Could not create resource (${response.status}).`);}const created = await response.json();setFormData({ ...initialForm });setSaveMessage(`Created ${created.title}.`);refetch();} catch (err) {setSaveError(err.message);} finally {setIsSaving(false);}}return (Enter a distinctive title and submit once. You should see Saving, a confirmation, and then the resource in the refreshed list. Navigate to Directory, clear any filters, and find that resource there too.
This backend writes to its
resources.json, so a successful create survives a page refresh. The POST belongs in the submit handler because it is caused by that user action; placing it in a mounting Effect could create unwanted duplicates.Stop the backend and try another create. The form should show an error and retain the title. Restart the backend before continuing. Keep list-loading errors separate from save errors so a failed refresh isn’t mistaken for a failed create.
-
Check the finished routes.
Check Expected result Open /Directory with working filters and details Open /admindirectly and refreshManagement page on the Vite development server Use navigation, Back, and Forward Correct page and active link Navigate away during a slow list request Obsolete request is cleaned up Create and then return to Directory New resource appears in the fetched list Resize to narrow and wide widths Directory grid and full-width Admin remain readable Use the keyboard for links and form submission too. When deploying later, a host serving
BrowserRouterURLs must return the app’s HTML for paths such as/admin; Vite provides this during development.
What we’ve accomplished
Section titled “What we’ve accomplished”We’ve separated page responsibilities while keeping a shared header and layout. The router chooses a page; each page owns its relevant state and requests. The guided activity supports listing and creating resources. Updating an existing resource is the next independent challenge.
An Admin route is a page organization choice here. This classroom backend has no authentication or authorization; naming a path /admin doesn’t restrict access.
Practice
Section titled “Practice”Complete the management page
Section titled “Complete the management page”Extend the resource directory’s Admin page using the existing backend contract:
- Add controlled inputs for category, summary, location, hours, contact, Virtual options, and Open now. Use
checkedfor boolean fields, and keep labels connected to their inputs. - Let a user choose an existing resource with a keyboard-accessible Edit button. Populate the form and track
editingId, usingnullfor create mode. - Submit new resources with
POST /resources; update an existing resource withPUT /resources/:id, encoding the id in the URL. PUT requires the complete set of fields and must retain the existing id. - Make create and edit modes clear through headings or button labels. Add Cancel editing to clear the id, form, and old feedback.
- Retain the entered values on failure, disable submission while saving, and refresh the list after success.
Check that editing changes one existing record instead of adding a duplicate. Confirm that Cancel returns to create mode. If you edit the currently selected resource, revisit the saved-snapshot limitation from Lesson 16 and decide how to refresh those details.
As a routing extension, add a * fallback route inside the shared layout that shows a helpful not-found message and a link to Directory.
Homework: organize Users and Posts into pages
Section titled “Homework: organize Users and Posts into pages”Continue your existing project using today’s homework.md. Create a Users and Posts page at / and a management page at /users/manage, with shared layout and navigation.
Your management page should list users and support create/edit modes with controlled name, email, phone, and website fields. Include clear feedback and a way to cancel editing or clear the form. Preserve user search, selected-user persistence, and loading posts on the main page.
JSONPlaceholder simulates writes; it doesn’t permanently save your changes. Use the homework’s local-state approach, or combine simulated requests with local state updates. Don’t expect refetching its user list to return a newly created user. If you simulate POST requests, assign each locally added user a unique client id so repeated creations have distinct React keys.
Verify both URLs, direct refreshes, Back/Forward navigation, creating, editing, cancelling, and the existing Users and Posts behaviour. Keep route parameters, loaders, and actions for later lessons. Record your route structure and how simulated changes are stored in your README.md, then follow the starter’s submission instructions.
Answered: 0 / 0 (0%)