📘 Introduction
When building single-page applications (SPAs) with React, one common challenge is managing navigation between different pages without reloading the browser.
That’s where React Router comes to the rescue! 🦸♂️
React Router is the standard routing library for React that enables you to handle navigation and render components based on URL paths — all without refreshing the page.
In short, React Router helps your React app behave like a multi-page site, while actually being a single-page application (SPA). 🚀
💡 Why Do We Need React Router?
In traditional websites 🌐, clicking a link reloads the entire page from the server.
But in React, we want:
✨ Smooth transitions
✨ No page reloads
✨ Better user experience
✨ Functional browser navigation (Back/Forward buttons)
React Router makes this possible by keeping everything on the client-side and updating only what’s needed.
⚙️ Installation
You can easily add React Router to your project by running:
npm install react-router-dom
>🧠 Note:
react-router-dom → for web apps
react-router-native → for React Native🧩 Core Components of React Router
Let’s explore the most important parts of React Router 👇
🏠 1. BrowserRouter
This is the main wrapper that enables routing functionality in your React app.
import { BrowserRouter } from "react-router-dom";
function App() {
return (
<BrowserRouter>
<h1>My React App</h1>
</BrowserRouter>
);
}
It acts like a container for your entire application.
🛤️ 2. Routes and Route
The Routes component holds multiple Route definitions.
Each Route maps a path to a component.
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "./Home";
import About from "./About";
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
);
}📍 / → Home Page
📍 /about → About Page
🔗 3. Link and NavLink
Use Link instead of HTML <a> tags for smooth navigation without page reloads.
import { Link } from "react-router-dom";
function Navbar() {
return (
<nav>
<Link to="/">🏡 Home</Link> | <Link to="/about">ℹ️ About</Link>
</nav>
);
}
Want to highlight the active link? Use NavLink:
<NavLink
to="/about"
className={({ isActive }) => (isActive ? "active" : "")}
>
⭐ About
</NavLink>🧭 4. useNavigate Hook
For programmatic navigation, use the useNavigate() hook.
Example: redirecting after login ✅
import { useNavigate } from "react-router-dom";
function Login() {
const navigate = useNavigate();
const handleLogin = () => {
// logic
navigate("/dashboard");
};
return <button onClick={handleLogin}>🔓 Login</button>;
}

Join the conversation! Your thoughts help the community grow.