नमस्ते दोस्तों! 🙏
स्वागत है The Easy Master पर!
क्या तुमने कभी सोचा है – React ek Single Page Application (SPA) है, तो multiple pages kaise banayein?
Normal websites (like Amazon, Flipkart) mein:
- Home page →
/ - Products page →
/products - Product detail →
/products/101 - Cart page →
/cart
Yeh sab different URLs हैं – aur jab tum link click karte ho, toh page reload hota hai।
React Router v6 Routing Hindi में समझना बहुत जरूरी है क्योंकि:
- React apps mein multi-page feel without page reload – smooth experience
- URL share karna – kisi ko specific page ka link bhej sakte ho
- Browser navigation – back/forward buttons kaam karte hain
- SEO better – different URLs for different content
- 99% React apps routing use karte hain
Aaj kya seekhoge?
| Topic | Kya Seekhega? |
|---|---|
| React Router v6 Setup | Installation aur basic configuration |
| Routes & Route | Different URLs ke liye components |
| Link & NavLink | Page reload ke bina navigation |
| Nested Routes | Layouts ke saath child pages |
| Dynamic Routes | URLs with parameters (/user/:id) |
| Protected Routes | Authentication ke saath page guard |
| Programmatic Navigation | useNavigate hook se navigation |
Kya tumhe pata hai?
React Router v6 ne v5 se bohot changes kiye hain – ab code shorter aur easier hai। Switch ab Routes hai, aur useHistory ab useNavigate!
तो चलिए शुरू करते हैं – React Router v6 Routing Hindi सीखने का सफर! 🚀
Table of Contents
1. React Router v6 Routing Hindi – Introduction
React Router ek library hai jo React apps mein routing add karti hai – bina page reload ke different URLs show karne ke liye।
React Router v6 vs Traditional Websites:
| Feature | Traditional Website | React Router v6 |
|---|---|---|
| Page reload | Har navigation par reload hota hai | No reload – smooth |
| Navigation speed | Slow (waits for server) | Instant |
| State preservation | Lost on navigation | Preserved |
| User experience | Feels like old web | Feels like app |
| Back/Forward buttons | Works | Works |
| Deep linking | Works | Works |
React Router v6 Routing Hindi mein hum ek complete multi-page app banayenge – Home, About, Products, Product Detail, Contact, aur Dashboard with authentication।
2. Installation aur Setup
Step 1: React Router v6 Install Karna
# NPM se install
npm install react-router-dom
# Yarn se install
yarn add react-router-domStep 2: Package.json Check Karna
{
"dependencies": {
"react-router-dom": "^6.20.0" // v6 or higher
}
}3. BrowserRouter – App ko Router Provide Karna
BrowserRouter whole app ko routing capability deta hai।
main.jsx – Router Setup:
// src/main.jsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom'; // ✅ Import BrowserRouter
import App from './App';
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<BrowserRouter> {/* ✅ Wrap App with BrowserRouter */}
<App />
</BrowserRouter>
</React.StrictMode>
);Alternative Router Types:
| Router | Use Case |
|---|---|
| BrowserRouter | Most common – for web apps |
| HashRouter | Static file hosting (no server config) |
| MemoryRouter | Testing / React Native |
| StaticRouter | Server-side rendering |
4. Routes aur Route – Pages Define Karna

Routes container hai – jisme hum Route components define karte hain।
App.jsx – Basic Routes:
// src/App.jsx
import { Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';
import Contact from './pages/Contact';
import Products from './pages/Products';
function App() {
return (
<div className="app">
<h1>My React App</h1>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
<Route path="/products" element={<Products />} />
</Routes>
</div>
);
}
export default App;Page Components:
// src/pages/Home.jsx
function Home() {
return (
<div>
<h2>Home Page</h2>
<p>Welcome to our website!</p>
</div>
);
}
export default Home;
// src/pages/About.jsx
function About() {
return (
<div>
<h2>About Us</h2>
<p>We are learning React Router v6!</p>
</div>
);
}
export default About;5. Link aur NavLink – Navigation without Reload
Link – page reload ke bina navigation के लिए (replaces <a href="">)
NavLink – Link jaisa hai, lekin active state deta hai (styling ke liye)
Header Component with Navigation:
// src/components/Header.jsx
import { Link, NavLink } from 'react-router-dom';
function Header() {
return (
<header>
<nav>
{/* Simple Link */}
<Link to="/">Home</Link>
<Link to="/about">About</Link>
{/* NavLink with active styling */}
<NavLink
to="/products"
className={({ isActive }) => isActive ? 'active-link' : ''}
style={({ isActive }) => ({
color: isActive ? '#61DAFB' : 'white',
fontWeight: isActive ? 'bold' : 'normal'
})}
>
Products
</NavLink>
<NavLink to="/contact">Contact</NavLink>
</nav>
</header>
);
}
export default Header;Complete App with Navigation:
// src/App.jsx
import { Routes, Route } from 'react-router-dom';
import Header from './components/Header';
import Footer from './components/Footer';
import Home from './pages/Home';
import About from './pages/About';
import Contact from './pages/Contact';
import Products from './pages/Products';
function App() {
return (
<div className="app">
<Header />
<main>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
<Route path="/products" element={<Products />} />
</Routes>
</main>
<Footer />
</div>
);
}
export default App;CSS for Active Link:
/* src/App.css */
.active-link {
color: #61DAFB !important;
border-bottom: 2px solid #61DAFB;
}
nav a {
color: white;
text-decoration: none;
margin: 0 15px;
padding: 5px 10px;
}
nav a:hover {
color: #61DAFB;
}6. Nested Routes – Layouts aur Child Pages
Nested Routes – common layout share karne के लिए (जैसे header + sidebar same रहे, सिर्फ content change हो)
Layout Component:
// src/layouts/ProductsLayout.jsx
import { Outlet, NavLink } from 'react-router-dom';
function ProductsLayout() {
return (
<div className="products-layout">
<h2>Products Section</h2>
<div className="products-sidebar">
<NavLink to="all">All Products</NavLink>
<NavLink to="electronics">Electronics</NavLink>
<NavLink to="clothing">Clothing</NavLink>
<NavLink to="books">Books</NavLink>
</div>
<div className="products-content">
<Outlet /> {/* Child routes yahan render honge */}
</div>
</div>
);
}
export default ProductsLayout;App with Nested Routes:
// src/App.jsx
import { Routes, Route } from 'react-router-dom';
import ProductsLayout from './layouts/ProductsLayout';
import AllProducts from './pages/AllProducts';
import Electronics from './pages/Electronics';
import Clothing from './pages/Clothing';
import Books from './pages/Books';
function App() {
return (
<Routes>
<Route path="/products" element={<ProductsLayout />}>
<Route path="all" element={<AllProducts />} />
<Route path="electronics" element={<Electronics />} />
<Route path="clothing" element={<Clothing />} />
<Route path="books" element={<Books />} />
{/* Default nested route – /products par */}
<Route index element={<AllProducts />} />
</Route>
</Routes>
);
}URL Mapping:
| URL | Component Rendered |
|---|---|
/products | ProductsLayout + AllProducts (index) |
/products/all | ProductsLayout + AllProducts |
/products/electronics | ProductsLayout + Electronics |
/products/clothing | ProductsLayout + Clothing |
/products/books | ProductsLayout + Books |
7. Dynamic Routes – URL Parameters
Dynamic Routes – jab URL mein variable data ho (jaise /user/123, /product/101)
Dynamic Route Definition:
// src/App.jsx
import { Routes, Route } from 'react-router-dom';
import ProductDetail from './pages/ProductDetail';
import UserProfile from './pages/UserProfile';
function App() {
return (
<Routes>
{/* Dynamic route – :id parameter */}
<Route path="/product/:id" element={<ProductDetail />} />
{/* Multiple parameters */}
<Route path="/user/:userId/post/:postId" element={<UserPost />} />
{/* Optional parameter – ? means optional */}
<Route path="/profile/:username?" element={<Profile />} />
</Routes>
);
}useParams Hook – Parameters Access Karna:
// src/pages/ProductDetail.jsx
import { useParams } from 'react-router-dom';
import { useState, useEffect } from 'react';
function ProductDetail() {
const { id } = useParams(); // Extract id from URL
const [product, setProduct] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
// Fetch product using the id
fetch(`/api/products/${id}`)
.then(res => res.json())
.then(data => {
setProduct(data);
setLoading(false);
});
}, [id]); // Re-fetch when id changes
if (loading) return <div>Loading product...</div>;
return (
<div>
<h1>{product?.name}</h1>
<p>Price: ${product?.price}</p>
<p>Description: {product?.description}</p>
</div>
);
}
export default ProductDetail;Multiple Parameters Example:
// src/pages/UserPost.jsx
import { useParams } from 'react-router-dom';
function UserPost() {
const { userId, postId } = useParams();
return (
<div>
<h2>User ID: {userId}</h2>
<h3>Post ID: {postId}</h3>
<p>Showing post {postId} by user {userId}</p>
</div>
);
}Link to Dynamic Routes:
// src/components/ProductCard.jsx
import { Link } from 'react-router-dom';
function ProductCard({ product }) {
return (
<div className="product-card">
<h3>{product.name}</h3>
<p>${product.price}</p>
<Link to={`/product/${product.id}`}>
View Details
</Link>
</div>
);
}8. useNavigate Hook – Programmatic Navigation
useNavigate – button click, form submit, ya logic ke baad navigation के लिए।
// src/pages/Login.jsx
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
function Login() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const navigate = useNavigate(); // ✅ Get navigate function
const handleLogin = async (e) => {
e.preventDefault();
// API call for login
const response = await fetch('/api/login', {
method: 'POST',
body: JSON.stringify({ email, password })
});
if (response.ok) {
// ✅ Navigate to dashboard after successful login
navigate('/dashboard');
} else {
alert('Login failed!');
}
};
return (
<form onSubmit={handleLogin}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Email"
/>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Password"
/>
<button type="submit">Login</button>
</form>
);
}navigate ke options:
function NavigationExample() {
const navigate = useNavigate();
// 1. Simple navigation
const goToHome = () => navigate('/');
// 2. Go back (previous page)
const goBack = () => navigate(-1);
// 3. Go forward
const goForward = () => navigate(1);
// 4. Replace current history (back button se wapas na aaye)
const replacePage = () => navigate('/new-page', { replace: true });
// 5. With state (data pass karna)
const goWithState = () => {
navigate('/dashboard', {
state: { from: 'login', userId: 123 }
});
};
return (
<div>
<button onClick={goToHome}>Home</button>
<button onClick={goBack}>Back</button>
<button onClick={goForward}>Forward</button>
</div>
);
}Receiving State on Other Page:
// src/pages/Dashboard.jsx
import { useLocation } from 'react-router-dom';
function Dashboard() {
const location = useLocation();
const state = location.state; // { from: 'login', userId: 123 }
return (
<div>
<h2>Dashboard</h2>
{state && <p>You came from: {state.from}</p>}
</div>
);
}9. useParams Hook – URL Parameters Access Karna
(Dynamic Routes section mein already cover ho gaya – but additional tips)
// src/pages/SearchResults.jsx
import { useParams, useLocation } from 'react-router-dom';
function SearchResults() {
const { query } = useParams(); // URL se parameter
const location = useLocation(); // Query parameters ke liye
const searchParams = new URLSearchParams(location.search);
const page = searchParams.get('page'); // ?page=2
return (
<div>
<h2>Search Results for: {query}</h2>
<p>Page: {page || 1}</p>
</div>
);
}10. Protected Routes – Authentication Guard
Protected Route – sirf logged-in users ko page dikhana।
ProtectedRoute Component:
// src/components/ProtectedRoute.jsx
import { Navigate } from 'react-router-dom';
function ProtectedRoute({ children }) {
const isLoggedIn = localStorage.getItem('token'); // Check authentication
if (!isLoggedIn) {
// Not logged in – redirect to login
return <Navigate to="/login" replace />;
}
// Logged in – show the page
return children;
}
export default ProtectedRoute;Using ProtectedRoute:
// src/App.jsx
import { Routes, Route } from 'react-router-dom';
import ProtectedRoute from './components/ProtectedRoute';
import Dashboard from './pages/Dashboard';
import Profile from './pages/Profile';
import Settings from './pages/Settings';
import Login from './pages/Login';
function App() {
return (
<Routes>
{/* Public routes */}
<Route path="/login" element={<Login />} />
<Route path="/" element={<Home />} />
{/* Protected routes */}
<Route path="/dashboard" element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
} />
<Route path="/profile" element={
<ProtectedRoute>
<Profile />
</ProtectedRoute>
} />
<Route path="/settings" element={
<ProtectedRoute>
<Settings />
</ProtectedRoute>
} />
</Routes>
);
}Advanced Protected Route with Role-Based Access:
// src/components/RoleBasedRoute.jsx
import { Navigate } from 'react-router-dom';
function RoleBasedRoute({ children, allowedRoles }) {
const user = JSON.parse(localStorage.getItem('user'));
if (!user) {
return <Navigate to="/login" replace />;
}
if (!allowedRoles.includes(user.role)) {
return <Navigate to="/unauthorized" replace />;
}
return children;
}
// Usage
<Route path="/admin" element={
<RoleBasedRoute allowedRoles={['admin']}>
<AdminDashboard />
</RoleBasedRoute>
} />
<Route path="/moderator" element={
<RoleBasedRoute allowedRoles={['admin', 'moderator']}>
<ModeratorPanel />
</RoleBasedRoute>
} />11. 404 Page – Not Found Route
404 Page – jab koi matching route na mile।
// src/pages/NotFound.jsx
import { Link } from 'react-router-dom';
function NotFound() {
return (
<div style={{ textAlign: 'center', marginTop: '50px' }}>
<h1>404</h1>
<h2>Page Not Found</h2>
<p>Sorry, the page you are looking for does not exist.</p>
<Link to="/">Go Back to Home</Link>
</div>
);
}
export default NotFound;Catch-All Route:
// src/App.jsx
import { Routes, Route } from 'react-router-dom';
import NotFound from './pages/NotFound';
function App() {
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/products" element={<Products />} />
{/* Catch-all route – must be LAST */}
<Route path="*" element={<NotFound />} />
</Routes>
);
}12. Real-world Project – Complete E-commerce Routing
Complete App Structure:
// src/App.jsx
import { Routes, Route } from 'react-router-dom';
import Layout from './components/Layout';
import ProtectedRoute from './components/ProtectedRoute';
import Home from './pages/Home';
import Products from './pages/Products';
import ProductDetail from './pages/ProductDetail';
import Cart from './pages/Cart';
import Checkout from './pages/Checkout';
import Login from './pages/Login';
import Register from './pages/Register';
import Dashboard from './pages/Dashboard';
import Orders from './pages/Orders';
import Profile from './pages/Profile';
import NotFound from './pages/NotFound';
function App() {
return (
<Routes>
<Route path="/" element={<Layout />}>
{/* Public routes */}
<Route index element={<Home />} />
<Route path="products" element={<Products />} />
<Route path="product/:id" element={<ProductDetail />} />
<Route path="cart" element={<Cart />} />
<Route path="login" element={<Login />} />
<Route path="register" element={<Register />} />
{/* Protected routes (require login) */}
<Route path="checkout" element={
<ProtectedRoute>
<Checkout />
</ProtectedRoute>
} />
<Route path="dashboard" element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
} />
<Route path="orders" element={
<ProtectedRoute>
<Orders />
</ProtectedRoute>
} />
<Route path="profile" element={
<ProtectedRoute>
<Profile />
</ProtectedRoute>
} />
{/* 404 catch-all */}
<Route path="*" element={<NotFound />} />
</Route>
</Routes>
);
}
export default App;Layout Component (with Navbar and Footer):
// src/components/Layout.jsx
import { Outlet } from 'react-router-dom';
import Navbar from './Navbar';
import Footer from './Footer';
function Layout() {
return (
<div className="app-layout">
<Navbar />
<main className="main-content">
<Outlet />
</main>
<Footer />
</div>
);
}
export default Layout;Navbar with Cart Count:
// src/components/Navbar.jsx
import { Link, NavLink } from 'react-router-dom';
import { useContext } from 'react';
import { CartContext } from '../contexts/CartContext';
function Navbar() {
const { cartCount } = useContext(CartContext);
const isLoggedIn = localStorage.getItem('token');
return (
<nav className="navbar">
<Link to="/" className="logo">ShopEasy</Link>
<div className="nav-links">
<NavLink to="/">Home</NavLink>
<NavLink to="/products">Products</NavLink>
<NavLink to="/cart">
Cart {cartCount > 0 && <span className="cart-badge">{cartCount}</span>}
</NavLink>
{isLoggedIn ? (
<>
<NavLink to="/dashboard">Dashboard</NavLink>
<button onClick={handleLogout}>Logout</button>
</>
) : (
<>
<NavLink to="/login">Login</NavLink>
<NavLink to="/register">Register</NavLink>
</>
)}
</div>
</nav>
);
}13. Common Mistakes + Solutions
Mistake 1: Forgetting to wrap App with BrowserRouter
// ❌ Error: useRoutes() may be used only in the context of a <Router> component
ReactDOM.render(<App />, document.getElementById('root'));
// ✅ Correct
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);Mistake 2: Using <a> instead of <Link>
// ❌ Page reload hoga – SPA advantage khatam
<a href="/products">Products</a>
// ✅ No reload – smooth navigation
<Link to="/products">Products</Link>Mistake 3: Routes order – Catch-all route beech mein
// ❌ Catch-all route pehle – baaki routes kabhi match nahi honge
<Routes>
<Route path="*" element={<NotFound />} />
<Route path="/products" element={<Products />} />
</Routes>
// ✅ Catch-all route LAST mein
<Routes>
<Route path="/products" element={<Products />} />
<Route path="*" element={<NotFound />} />
</Routes>Mistake 4: Nested routes mein element bhoolna
// ❌ Missing element prop on parent
<Route path="/products">
<Route path="all" element={<AllProducts />} />
</Route>
// ✅ Parent route needs element (with Outlet)
<Route path="/products" element={<ProductsLayout />}>
<Route path="all" element={<AllProducts />} />
</Route>Mistake 5: useNavigate outside Router context
// ❌ Error: useNavigate() may be used only in context of Router
function MyComponent() {
const navigate = useNavigate(); // Error if not inside Router
}
// ✅ Make sure component is inside BrowserRouter14. Quick Cheat Sheet
| Component/Hook | Syntax | Purpose |
|---|---|---|
| BrowserRouter | <BrowserRouter><App /></BrowserRouter> | Wrap entire app |
| Routes | <Routes>…</Routes> | Container for Route components |
| Route | <Route path="/about" element={<About />} /> | Define page |
| Link | <Link to="/about">About</Link> | Navigation without reload |
| NavLink | <NavLink to="/about">About</NavLink> | Link with active state |
| Outlet | <Outlet /> | Render nested routes |
| useParams | const { id } = useParams() | Get URL parameters |
| useNavigate | const navigate = useNavigate(); navigate('/') | Programmatic navigation |
| useLocation | const location = useLocation() | Get current URL info |
| Navigate | <Navigate to="/login" replace /> | Redirect |
| Index Route | <Route index element={<Home />} /> | Default nested route |
| Catch-all | <Route path="*" element={<NotFound />} /> | 404 page |
15. FAQ
Q1: React Router v6 Routing Hindi में सबसे important change kya hai v5 se?Switch → Routes, useHistory → useNavigate, exact prop ki zaroorat nahi (v6 exact by default hai)
Q2: Link aur NavLink mein kya antar hai?
NavLink active state deta hai (styling ke liye), Link sirf navigation करता है।
Q3: Nested Routes kyun use karein?
Common layout (header, sidebar, footer) share karne ke liye – code duplicate nahi karna padta।
Q4: Dynamic routes mein multiple parameters kaise handle karein?/user/:userId/post/:postId – useParams se dono mil jayenge: { userId, postId }
Q5: Protected Route kaise banayein?
Component banayein jo authentication check kare – agar logged in nahi toh <Navigate to="/login" />
Q6: useNavigate vs <Link> – kab kya use karein?<Link> – JSX mein direct navigation के लिए। useNavigate – button click, form submit, ya logic ke baad navigation के लिए।
Q7: 404 page kaise implement karein?
Last route mein <Route path="*" element={<NotFound />} /> add karo।
Q8: URL se query parameters (?page=2&sort=asc) kaise read karein?useLocation() hook + new URLSearchParams(location.search)
Q9: Kya React Router v6 TypeScript ke saath kaam karta hai?
Haan, full TypeScript support hai – useParams<{ id: string }>()
Q10: React Router v6 mein lazy loading kaise karein?React.lazy() + Suspense with Route: <Route path="/about" element={<Suspense fallback={<div>Loading...</div>}><About /></Suspense>} />
16. Conclusion
बहुत बढ़िया दोस्तों! आज हमने React Router v6 Routing Hindi को पूरी detail में समझा।
Quick Recap:
| Concept | Key Takeaway |
|---|---|
| BrowserRouter | App ko Router provide karna |
| Routes + Route | Pages define karna |
| Link / NavLink | Navigation without reload |
| Nested Routes | Layouts ke saath child pages |
| Dynamic Routes | URL parameters (/user/:id) |
| useNavigate | Programmatic navigation |
| Protected Routes | Authentication guard |
Mera personal experience:
जब मैंने पहली बार React Router सीखा, तो v5 use karta tha – Switch, exact, useHistory – thoda confusing था। v6 ने bohot simplify kar diya। अब Routes और useNavigate – code bohot cleaner है।
Tum bhi ye project zaroor karo:
- ✅ E-commerce website routing
- ✅ Blog with nested routes (categories)
- ✅ Dashboard with protected routes
- ✅ Multi-step form with navigation
अब तुम्हारी बारी है!
नीचे comment में बताओ:
- तुम्हें nested routes easy lage ya dynamic routes?
- क्या तुमने कभी protected route implement kiya hai?
- अगला topic क्या चाहिए? (Context API? Redux? Tailwind CSS?)
The Easy Master पर बने रहो। Happy Routing! ⚛️🚀
Resources
Additional Resources
- Master ES6: A Complete Feature Guide with Examples
- Top 10 React Libraries and Tools Every Developer Must Know in 2025
- Top 10 Free APIs for Practice in 2026
- JavaScript Deep Dive 2026: Closures, Promises & Event Loop
- TypeScript Modules Export Import Best Practices – समझे आसान भाषा में 2026
- React.js Kya Hai? JSX aur Components Samjhe – Beginner Guide 2026
- React Props and State Data Flow Hindi – समझे आसान भाषा में 2026