Tutorials

How to Use React Router: A Beginner's Walkthrough

React Router tutorial diagram of a layout route with nested child pages

This React Router tutorial builds a tiny "team directory" app from an empty Vite project. By the end you will have a shared layout, a home page, a list of people, a detail page for each person read from the URL, an active menu, a redirect after a form, and a not-found page. That covers most of what everyday apps need from React Router.

We use Declarative Mode, the simplest of React Router's three modes, with React Router 8.5.3. If you have not installed it yet, follow How to Download and Install React Router first, then come back.

Step 1: Create the project

npm create vite@latest team-directory -- --template react
cd team-directory
npm i
npm i react-router

Open src/main.jsx and wrap the app in BrowserRouter. This component connects React Router to the browser's address bar and history:

import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router";
import App from "./App";

createRoot(document.getElementById("root")).render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);

You only do this once, at the very top. Every hook and link in the rest of the app depends on it.

Step 2: Plan the URLs

Before writing components, decide which URLs the app will have. It keeps the route tree tidy:

  • / shows a welcome page.
  • /people lists everyone.
  • /people/:personId shows one person, for example /people/ada.
  • /people/new shows a form to add someone.
  • Anything else shows "Page not found".

Step 3: Build a layout with Outlet

Almost every app has parts that never change between pages, such as a header and a menu. In React Router, those go in a layout route. The layout renders <Outlet /> wherever the current child page should appear.

// src/Layout.jsx
import { NavLink, Outlet } from "react-router";

export default function Layout() {
  return (
    <div className="shell">
      <header>
        <strong>Team Directory</strong>
        <nav>
          <NavLink to="/" end>Home</NavLink>
          <NavLink to="/people">People</NavLink>
        </nav>
      </header>
      <main>
        <Outlet />
      </main>
    </div>
  );
}

Notice NavLink instead of Link. It behaves the same but adds an active class when its URL matches, so you can highlight the current menu item with plain CSS: nav a.active { font-weight: 700; }. The end prop on the Home link stops it from being "active" on every page, since every URL starts with /.

Step 4: Declare the routes

Now replace src/App.jsx with the route tree. Child routes are nested inside the layout route, and their paths are relative to the parent:

import { Routes, Route } from "react-router";
import Layout from "./Layout";
import Home from "./Home";
import People from "./People";
import Person from "./Person";
import NewPerson from "./NewPerson";
import NotFound from "./NotFound";

export default function App() {
  return (
    <Routes>
      <Route element={<Layout />}>
        <Route index element={<Home />} />
        <Route path="people" element={<People />} />
        <Route path="people/new" element={<NewPerson />} />
        <Route path="people/:personId" element={<Person />} />
        <Route path="*" element={<NotFound />} />
      </Route>
    </Routes>
  );
}

Three details worth knowing:

  • The layout route has no path. It only wraps its children, so it never adds anything to the URL.
  • index marks the default child, shown at the parent's own URL (here /).
  • Order does not decide the winner. React Router ranks routes, so people/new beats people/:personId for the URL /people/new because a static segment scores higher than a dynamic one.

Step 5: Add some data and the list page

Keep the data simple for now, in src/data.js:

export const people = [
  { id: "ada", name: "Ada Lovelace", role: "Engineer" },
  { id: "grace", name: "Grace Hopper", role: "Architect" },
  { id: "alan", name: "Alan Turing", role: "Researcher" },
];

The list page links to each person with Link. Relative paths work here: to={p.id} inside /people resolves to /people/ada.

// src/People.jsx
import { Link } from "react-router";
import { people } from "./data";

export default function People() {
  return (
    <>
      <h1>People</h1>
      <ul>
        {people.map((p) => (
          <li key={p.id}><Link to={p.id}>{p.name}</Link></li>
        ))}
      </ul>
      <Link to="new">Add a person</Link>
    </>
  );
}

Step 6: Read the URL with useParams

The detail page needs to know which person to show. The :personId segment in the route path becomes a key in the object returned by useParams:

// src/Person.jsx
import { useParams, Link } from "react-router";
import { people } from "./data";

export default function Person() {
  const { personId } = useParams();
  const person = people.find((p) => p.id === personId);

  if (!person) return <p>No one called "{personId}" works here.</p>;

  return (
    <article>
      <h1>{person.name}</h1>
      <p>{person.role}</p>
      <Link to=".." relative="path">Back to people</Link>
    </article>
  );
}

Params are always strings. If your IDs are numbers, convert them with Number(personId) before comparing. The relative="path" option makes .. go up one URL segment (from /people/ada to /people) rather than up one route level.

Step 7: Redirect in code with useNavigate

Links cover clicks. For everything else, such as moving the user after a form is saved, use the useNavigate hook:

// src/NewPerson.jsx
import { useNavigate } from "react-router";
import { people } from "./data";

export default function NewPerson() {
  const navigate = useNavigate();

  function handleSubmit(e) {
    e.preventDefault();
    const name = new FormData(e.currentTarget).get("name");
    const id = String(name).toLowerCase().replace(/\s+/g, "-");
    people.push({ id, name, role: "New hire" });
    navigate(`/people/${id}`, { replace: true });
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>Name <input name="name" required /></label>
      <button>Save</button>
    </form>
  );
}

{ replace: true } replaces the form page in history, so pressing Back after saving does not return the user to an empty form. Call navigate(-1) to go back one step, just like the browser's Back button.

Step 8: Handle unknown URLs

The path="*" route catches anything that no other route matched. Give it a helpful message and a way home:

// src/NotFound.jsx
import { Link } from "react-router";

export default function NotFound() {
  return (
    <>
      <h1>Page not found</h1>
      <Link to="/">Go home</Link>
    </>
  );
}

Because it sits inside the layout route, the header and menu still show on the not-found page.

Step 9: Run and test it

Start the dev server with npm run dev and try these checks:

  1. Click People: the menu item turns bold and the list appears, without a page reload.
  2. Open a person, then press the browser's Back button: you return to the list.
  3. Type /people/grace straight into the address bar: the detail page loads directly.
  4. Add a person: you land on their page, and Back skips the form.
  5. Visit /nowhere: the not-found page shows inside the layout.

Download React Router 8.5.3

Where to go from here

You now know the core pieces: BrowserRouter, Routes, Route, Link, NavLink, Outlet, useParams and useNavigate. Next steps worth exploring:

  • Query strings for search and filters with useSearchParams.
  • Data Mode, which moves data fetching into route loader functions so pages render with their data ready.
  • Framework Mode, if you want server rendering and type-safe routes.

React Router key features explained gives an overview of all of these, and Best uses for React Router shows how real apps combine them. If something in this walkthrough throws an error, check common React Router errors and fixes.

Get React Router 8.5.3: one npm command, or the verified package download.

Download

Tivari

Professional content writer

Tivari is a professional content writer who covers web development tools, with a focus on turning technical documentation into clear, step-by-step articles. Every command and code sample in Tivari's articles is run against the current React Router release before publishing. About the writer and how we test.

Related articles