Home / Learn React / Routing with React Router

Routing with React Router

A single page app shows different screens for different URLs without reloading. React Router maps URLs to components.

In shortInstall react-router, wrap the app in a router, declare routes, and use Link instead of a tags for internal navigation.

Theory in plain words

Client side navigationClick a LinkHistory APIchanges the URLRouter matchesthe routeComponent swapsno page reload
Client side navigation

What it is

A router reads the browser URL and renders the matching component. Link changes the URL with the History API, without a full page load.

Why we use it

Users expect bookmarkable URLs and the back button to work. Without a router, everything lives on one URL.

How it works

The router listens to URL changes and renders the matching Route. Dynamic parts such as /users/:id are read with useParams.

Where it is used

  • Any multi page feeling app: dashboards, shops, admin panels
A basic router
npm install react-router

import { BrowserRouter, Routes, Route, Link, NavLink, useParams } from "react-router";

function User() { const { id } = useParams(); return <h2>User {id}</h2>; }

<BrowserRouter>
  <nav><NavLink to="/">Home</NavLink> <Link to="/users/7">User 7</Link></nav>
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/users/:id" element={<User />} />
    <Route path="*" element={<NotFound />} />
  </Routes>
</BrowserRouter>

Hosting note for Hostinger

With BrowserRouter, opening /users/7 directly asks the server for a file that does not exist. Add a rewrite rule in .htaccess so every unknown path serves index.html:

.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
Tip:If the app lives in a sub folder such as /my-app/, set basename="/my-app" on the router and base: "/my-app/" in vite.config.js.

Quick quiz

1. Which component changes the URL without a page reload?

2. How do you read /users/:id?

3. Why add an .htaccess rewrite?

Common questions

Which component changes the URL without a page reload?

Link. Link uses the History API.

How do you read /users/:id?

useParams. useParams returns the dynamic parts.

Why add an .htaccess rewrite?

So direct URLs serve index.html. The server has no file for client routes.