Skip to main content

React Router

React was specifically designed as a Single Page Application (SPA) library. This means the browser only technically loads a single HTML file index.html.

To create the illusion of navigating to different URLs (/about, /contact), the standard practice is to use a client-side routing library. The absolute industry standard for this is React Router.

Installation

npm install react-router-dom

Basic Setup

Client-side routing intercepts URL changes in the browser before they hit the server, and tells React to render a different component based on the URL path.

import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
import Home from './Home';
import About from './About';
import NotFound from './NotFound';

export default function App() {
return (
<BrowserRouter>
{/* Navigation Links */}
<nav>
<Link to="/">Home</Link>
<Link to="/about">About Us</Link>
</nav>

<main>
<Routes>
{/* Mapping URLs to distinct Components */}
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />

{/* Fallback Catch-all Route for 404s */}
<Route path="*" element={<NotFound />} />
</Routes>
</main>
</BrowserRouter>
);
}

Dynamic Routing

React Router allows you to create flexible URLs that capture dynamic variables, like user profiles or blog post IDs.

You designate a dynamic path using a colon :. Inside the component, you can extract the exact path value using the useParams hook.

// 1. Defining the route
<Route path="/users/:userId" element={<UserProfile />} />
// 2. Extracting the param inside UserProfile.jsx
import { useParams } from 'react-router-dom';

export default function UserProfile() {
// If the URL is '/users/123', userId evaluates to "123".
let { userId } = useParams();

return <div>Loading profile data for user: {userId}</div>;
}