React Router
React Router is a library used to handle navigation (routing) in React applications.
It allows you to create multiple pages in a Single Page Application (SPA) without reloading the page.
Why Use React Router?
Without routing:
Only one page UI
No navigation between components
With React Router:
Multiple pages (Home, About, Contact)
URL-based navigation
Dynamic routing
Nested layouts
Protected routes (Login required pages)
📦 Installation
npm install react-router-domBasic Setup
Wrap App with BrowserRouter
import { BrowserRouter } from "react-router-dom";
function App() {
return (
<BrowserRouter>
{/* Your app */}
</BrowserRouter>
);
}Core Components
1. Link
Used to navigate between pages
<Link to="/about">About</Link>🔹 2. Routes
Container for all routes
🔹 3. Route
Defines mapping between URL and component
<Routes>
<Route path="/" element={<Home />} />
</Routes>Basic Example
import { BrowserRouter, Routes, Route, Link } from "react-router-dom";
function Home() {
return <h1>Home Page</h1>;
}
function About() {
return <h1>About Page</h1>;
}
function Contact() {
return <h1>Contact Page</h1>;
}
function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link> |
<Link to="/about">About</Link> |
<Link to="/contact">Contact</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</BrowserRouter>
);
}Nested Routing
Route inside another route
Use Outlet
import { Outlet } from "react-router-dom";
function Products() {
return (
<div>
<h1>Products</h1>
<Outlet />
</div>
);
}Example
<Route path="/products" element={<Products />}>
<Route path="car" element={<CarProducts />} />
<Route path="bike" element={<BikeProducts />} />
</Route>URL Structure
/products/car→ CarProducts/products/bike→ BikeProducts
NavLink
Special Link with active state
import { NavLink } from "react-router-dom";
const style = ({ isActive }) => ({
color: isActive ? "blue" : "black",
fontWeight: isActive ? "bold" : "normal"
});
<NavLink to="/" style={style}>Home</NavLink>URL Parameters (Dynamic Routing)
Used for dynamic data in URL
Example URL:
/customer/Anil🔹 Route Setup
<Route path="/customer/:name" element={<User />} />🔹 Access Params
import { useParams } from "react-router-dom";
function User() {
const { name } = useParams();
return <h1>Hello {name}</h1>;
}Important Concepts
SPA (Single Page Application)
Page reload नहीं होता
Only component changes
🔸 Outlet
Child component render करने की जगह
🔸 Dynamic Routing
URL बदलता है → UI बदलता है
Interview Questions (Must Prepare)
What is React Router?
Difference between
LinkandNavLinkWhat is
Outlet?What are URL parameters?
Difference between SPA and MPA
How routing works internally?
Summary
React Router → Navigation system
BrowserRouter → Wrap app
Routes + Route → Define paths
Link → Navigation
NavLink → Active styling
Outlet → Nested routing
useParams → Dynamic data