Back
LearnReact — Build Modern Web AppsReact Router — multiple pages

React Router — multiple pages

2 min read

Real apps have multiple pages

So far our app is one screen. But real apps have pages — Home, About, Profile — each with its own URL. React itself does not handle URLs; the standard tool for that is React Router.

Setup

npm install react-router-dom

Defining routes

You wrap your app in a router and list your pages with Routes and Route:

import { BrowserRouter, Routes, Route } from "react-router-dom";

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/profile" element={<Profile />} />
      </Routes>
    </BrowserRouter>
  );
}

Each Route maps a URL path to a component. Visit /about, and React Router shows <About /> — without a full page reload.

Linking between pages

Do not use a normal <a> tag (it reloads the whole page and loses React's state). Use <Link> instead:

import { Link } from "react-router-dom";

function Navbar() {
  return (
    <nav>
      <Link to="/">Home</Link>
      <Link to="/about">About</Link>
    </nav>
  );
}

<Link> changes the page instantly, the React way — no reload.

Dynamic routes (a page per item)

Often you need one route that works for many items — like a profile per username:

<Route path="/user/:username" element={<UserPage />} />

Inside UserPage, read the value with the useParams hook:

import { useParams } from "react-router-dom";

function UserPage() {
  const { username } = useParams();
  return <h1>Profile of {username}</h1>;
}

Now /user/riya and /user/sam both work with one route.

React Router turns one React app into a multi-page site. Define <Route path element> pairs, navigate with <Link> (not <a>), and read URL parts with useParams.

Tip