React Routing (react-router-dom) – Complete Notes
Routing in React is used to navigate between components without reloading the page using
react-router-dom.
1. Installation
npm install react-router-dom
2. Basic Setup
import { BrowserRouter, Routes, Route } from "react-router-dom";
function Home() { return <h2>Home Page</h2>; }
function About() { return <h2>About Page</h2>; }
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
);
}
3. Navigation using Link
import { Link } from "react-router-dom";
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</nav>
Link prevents page reload unlike anchor tags.
4. useNavigate Hook
import { useNavigate } from "react-router-dom";
function Example(){
const navigate = useNavigate();
return <button onClick={() => navigate("/about")}>Go</button>;
}
5. Dynamic Routing
<Route path="/user/:id" element={<User />} />
import { useParams } from "react-router-dom";
function User(){
const { id } = useParams();
return <h2>User ID: {id}</h2>;
}
6. Nested Routes
<Route path="/dashboard" element={<Dashboard />}>
<Route path="profile" element={<Profile />} />
</Route>
7. Important Components
Component Purpose
BrowserRouter Wraps app
Routes Contains routes
Route Defines path
Link Navigation
useNavigate Programmatic navigation
useParams Get dynamic values
Summary
React Router allows navigation in single-page applications without page reload using routes and links.