React is a single-page application (SPA) library. Rather than requesting new HTML pages from a backend server on every navigation link click, React Router intercepts browser navigation events and dynamically swaps component views without reloading the page.
flowchart LR
URL["Browser URL (/users/42)"] --> Router["<BrowserRouter>"]
Router --> Routes["<Routes> Matching"]
Routes -- "/users/:id" --> Comp["<UserProfile /> Component"]
BrowserRouter, Routes, Route)First, install react-router-dom:
npm install react-router-dom
import React from 'react';
import { BrowserRouter, Routes, Route, Link, useParams, useNavigate } from 'react-router-dom';
function Home() {
return <h2>Home Dashboard View</h2>;
}
function UserDetail() {
// Extract URL route parameter (:id)
const { id } = useParams();
const navigate = useNavigate();
return (
<div>
<h2>User Profile #{id}</h2>
<button onClick={() => navigate('/')}>Back to Home</button>
</div>
);
}
function NotFound() {
return <h2>404 - Page Not Found</h2>;
}
export default function AppRouter() {
return (
<BrowserRouter>
<nav style={{ display: 'flex', gap: '1rem', padding: '1rem' }}>
<Link to="/">Home</Link>
<Link to="/users/101">User #101</Link>
<Link to="/users/202">User #202</Link>
</nav>
<main style={{ padding: '1rem' }}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/users/:id" element={<UserDetail />} />
<Route path="*" element={<NotFound />} />
</Routes>
</main>
</BrowserRouter>
);
}
<Link> Instead of Standard <a> Tags: Standard <a href="/about"> triggers a full browser reload, discarding in-memory React state. Always use React Router's <Link to="/about"> or <NavLink>.<Route path="*" element={<NotFound />} /> at the bottom of your <Routes> configuration.Implement programmatic navigation using the useNavigate() hook to automatically redirect users to /dashboard after successfully submitting a login form.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.