New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› React› Routing and Layouts

Routing and Layouts

💻 React

Add multiple pages with React Router and share a layout.

Lesson 7 of 9 Tutorial
0 of 9 completed

A single-page app still needs URLs. React Router maps a URL to a component without reloading the page.

By the end of this lesson you can:
  • 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-dom

Links 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>
  );
}
Warning On a static host, deep links need the server to return index.html for unknown paths. Check this before deploying.

Practice

  1. Add a /about route and a link to it.
  2. Create a /students/:id route that reads the id.
  3. 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

Exercise 1. Three-page site Medium
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.
React exercise-1.txt
Expected Output
Three working pages with shared navigation.

Lesson Nav

Lesson sections