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.
Theory in plain words
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
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:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]/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?
Link uses the History API.
2. How do you read /users/:id?
useParams returns the dynamic parts.
3. Why add an .htaccess rewrite?
The server has no file for client routes.
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.