Routing and Layouts
💻 ReactAdd multiple pages with React Router and share a layout.
A single-page app still needs URLs. React Router maps a URL to a component without reloading the page.
- Set up React Router.
- Use links and route parameters.
- Share a layout.
Setup
Install react-router-dom and wrap the app in a browser router.
import { BrowserRouter, Routes, Route } from "react-router-dom";
export default function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/students" element={<Students />} />
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
);
}Output
npm install react-router-domLinks and Parameters
Use Link instead of an anchor so the page does not reload. Read route parameters with useParams.
import { Link, useParams } from "react-router-dom";
<Link to="/students">All students</Link>
function StudentDetail() {
const { id } = useParams();
return <h1>Student {id}</h1>;
}Shared Layout
A layout route renders shared navigation and an Outlet where child routes appear.
function Layout() {
return (
<div>
<nav>
<Link to="/">Home</Link>
<Link to="/students">Students</Link>
</nav>
<main><Outlet /></main>
</div>
);
}Practice
- Add a /about route and a link to it.
- Create a /students/:id route that reads the id.
- Add a not-found page for unknown URLs.
Hands-on exercise
Set up routes for Home, Students and Student detail.
1. Share a navigation layout.
2. Link each list item to /students/:id.
3. Show a not-found page for unknown paths.
Recap
Routing maps URLs to components. Layouts share navigation and useParams reads the dynamic part of a URL.
Example
import { BrowserRouter, Routes, Route } from "react-router-dom";
export default function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/students" element={<Students />} />
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
);
}
Exercises
1. Share a navigation layout.
2. Link each list item to /students/:id.
3. Show a not-found page for unknown paths.
Expected Output
Three working pages with shared navigation.
Lesson Nav
React Course
0/9 lessons completed
- 1 Thinking in Components Tutorial
- 2 Props and Composition Tutorial
- 3 State and Events Tutorial
- 4 Lists, Keys and Conditional Rendering Tutorial
- 5 Forms in React Tutorial
- 6 Effects and Data Fetching Tutorial
- 7 Routing and Layouts Tutorial
- 8 Context and Shared State Tutorial
- 9 Project: A Student Dashboard Project