When building React applications, you often need navigation between different views without reloading the entire page. This is where react-router-dom comes in — it’s the standard library for handling routing in React apps.
What is react-router-dom?
react-router-dom is the DOM-specific version of React Router, designed for web applications. It enables:
- Client-side routing (changing views without full-page reloads)
- Dynamic route matching
- Nested routing
- Route parameters and query strings
- Navigation via code or UI links
Installation
npm install react-router-dom
or
yarn add react-router-dom
Basic Usage
1. Wrap your app in BrowserRouter
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Home from './Home';
import About from './About';
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Router>
);
}
export default App;
-
BrowserRouterenables HTML5 history API-based navigation. -
Routesis a container for all route definitions. -
Routemaps apathto a React component viaelement.
Navigation with Link
Instead of <a> tags, use Link from react-router-dom to prevent page reloads.
import { Link } from 'react-router-dom';
function Navbar() {
return (
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</nav>
);
}
Using useNavigate for Programmatic Navigation
import React from 'react';
import { useNavigate } from 'react-router-dom';
function ContactButton() {
const navigate = useNavigate();
return (
<button onClick={() => navigate('/contact')}>
Go to Contact
</button>
);
}
export default ContactButton;
-
useNavigate()returns a function that lets you navigate via JavaScript logic.
Dynamic Routes & URL Parameters
import { useParams } from 'react-router-dom';
function UserProfile() {
const { userId } = useParams();
return <h1>Profile of user {userId}</h1>;
}
<Route path="/user/:userId" element={<UserProfile />} />
- The
:userIdin the path is a dynamic segment. -
useParams()retrieves it inside the component.
Nested Routes
<Route path="/dashboard" element={<Dashboard />}>
<Route path="settings" element={<Settings />} />
</Route>
- Allows hierarchical navigation, like
/dashboard/settings.
Redirects with <Navigate />
<Route path="/old" element={<Navigate to="/new" replace />} />
- Redirects
/oldto/new.
When to Use react-router-dom
- When you need SPA (Single Page Application) navigation.
- When different UI views correspond to different URLs.
- When deep linking and browser history should be supported.
✅ Key takeaway:
react-router-dom is the backbone of routing in React apps. It allows seamless navigation, dynamic URLs, and programmatic control over route changes — making your SPA feel like a real multi-page app without the reload penalty.
Top comments (0)