✨ Quick Answer: React Router me Link aur NavLink kaise use karein? Hindi me seekhein dono ka difference aur active link styling ka step-by-step asan tarika.
React Router me Link aur NavLink kaise use karein? Is Hindi guide me navigation, active styling aur single page app routing ko detail me seekhein. क्या आप भी React App बनाते समय Navigation के लिए traditional HTML anchor tags यानी `` का use कर रहे हैं और हर click पर आपका browser full reload हो रहा है? दोस्तों, Single Page Application (SPA) का असली मज़ा तब तक नहीं आता जब तक pages बिना reload हुए पलक झपकते ही न बदलें! आज हम इसी समस्या को हमेशा के लिए खत्म करेंगे।Link और NavLink Components का use किया जाता है। Link normal navigation के लिए use होता है, जबकि NavLink का use active page link को CSS class या inline style देकर visually highlight करने के लिए किया जाता है।React Router में traditional HTML Anchor Tag (<a>) का use क्यों नहीं करना चाहिए?
जब हम HTML में standard navigation करते हैं, तो हम `` का use करते हैं। लेकिन React component के अंदर anchor tag का use करना एक बहुत बड़ी भूल हो सकती है। चलिए समझते हैं ऐसा क्यों है: जब भी user किसी anchor tag पर click करता है, तो browser default behavior के तहत dynamic request server पर भेजता है। इसके बाद server से पूरा का पूरा HTML document, CSS, और JavaScript files फिर से load होती हैं। इस structure को समझने के लिए नीचे दिए गए flow diagram को देखिए:Anchor Tag के नुकसान:
- State Loss: अगर आपने Redux, React Context API, या local React component state में कोई data store करके रखा है, तो anchor tag के reload होते ही वह सारा dynamic data हवा में गायब हो जाएगा।
- Slow User Experience: User को बार-बार loading screen देखनी पड़ेगी, जो modern user experience के नियमों के खिलाफ है।
- Server Load: बार-बार एक ही assets के लिए server को request भेजने से application performance पर भी असर पड़ता है।
React Router Navigation Setup करने का Step-by-Step तरीका क्या है?
दोस्तों, चलिए एकदम scratch से setup करते हैं ताकि आपको zero configuration errors आएं। हम React Router v6 का use करेंगे जो अभी current standard है।Step 1: Install React Router DOM
सबसे पहले अपने project directory में terminal खोलिए और React Router library को install कर लीजिए:npm install react-router-dom
Step 2: Wrap Application inside BrowserRouter
अब अपने application की wrapper file (आमतौर पर `main.jsx` या `index.js`) में `BrowserRouter` को wrap करना होगा। इसके बिना dynamic links काम नहीं करेंगे।import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App.jsx';
import './index.css';
import { BrowserRouter } from 'react-router-dom';
ReactDOM.createRoot(document.getElementById('root')).render(
);
Step 3: Define Routes in App.jsx
अब `App.jsx` में जाकर अपने routes set कर लेते हैं। हम Home, About, और Contact pages बनाएंगे।import { Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';
import Contact from './pages/Contact';
import Navbar from './components/Navbar';
function App() {
return (
);
}
export default App;
---
<Link> Component क्या है और इसे कैसे use करें?
`Link` component React Router का basic block है। इसका use user-triggered state navigation के लिए किया जाता है। React Router behind the scenes इस `Link` को standard `` anchor tag में ही convert करता है, लेकिन इसके default navigation payload को modify कर देता है ताकि page refresh न हो।Link Component का basic syntax:
import { Link } from 'react-router-dom';
// Component के अंदर इस तरह use करें:
<Link to="/about">About Us</Link>
यहां `to` attribute anchor tag के `href` attribute की तरह काम करता है। इसमें आप target URL reference define करते हैं।
Link के Advanced Attributes (Props):
- to (String or Object): यह destination specify करता है। आप इसमें string के अलावा configuration object भी pass कर सकते हैं:
<Link to={{ pathname: "/about", search: "?tab=details" }}>About</Link> - replace (Boolean): अगर आप Browser History stack में current page को replace करना चाहते हैं, तो इसका use करें। इसे true करने पर, back click करने पर user previous path पर वापस नहीं जा पाएगा:
<Link to="/dashboard" replace>Go to Dashboard</Link> - state (Any): यह feature सोने पर सुहागा है! इसकी मदद से आप बिना URL query params change किए location object में secure components dynamic raw state data pass कर सकते हैं:
<Link to="/contact" state={{ fromHomepage: true }}>Contact</Link>
<NavLink> Component क्या है और यह <Link> से कैसे अलग है?
अब बात करते हैं बड़े भाई यानी `NavLink` की। दोस्तों, सोचिए आप एक navigation menu बना रहे हैं। जब user "About" page पर हो, तो navigation header में "About" link active, highlighted या underlined दिखना चाहिए ताकि user को पता रहे कि वह अभी website के किस section में है। यही काम करने के लिए `NavLink` का creation हुआ है। यह built-in features के साथ आता है जो check करता है कि browser का active URL component के target dynamic endpoint `to` से match हो रहा है या नहीं।NavLink का default dynamic behavior:
जब browser URL और `NavLink` का `to` match करता है, तो `NavLink` component HTML output में automatically `active` class inject कर देता है।// Browser default output dynamically when on /about:
<a href="/about" class="active">About</a>
Dynamic Styling apply करने के तरीके:
आप `NavLink` में `className` या `style` dynamic arguments dynamic render features (functions) के ज़रिए styling control कर सकते हैं।1. Custom dynamic class handle करना:
import { NavLink } from 'react-router-dom';
function Navigation() {
return (
<NavLink
to="/about"
className={({ isActive }) => isActive ? 'my-custom-active-class' : 'normal-class'}
>
About
</NavLink>
);
}
2. Dynamic inline styles handle करना:
<NavLink
to="/contact"
style={({ isActive }) => ({
color: isActive ? '#06b6d4' : '#64748b',
fontWeight: isActive ? 'bold' : 'normal'
})}
>
Contact
</NavLink>
3. end prop का use (Very Important!):
ध्यान देने वाली बात ये है कि अगर आपका home link `/` है, तो वह हर path (जैसे `/about`, `/contact`) के साथ match हो जाएगा, क्योंकि `/` सभी routes के base structure में मौजूद होता है। इससे Home link हमेशा active दिखाई देगा! इसे रोकने के लिए हमें `end` prop का use करना होता है:<NavLink to="/" end className={({ isActive }) => isActive ? "active" : ""}>
Home
</NavLink>
`end` prop यह ensure करता है कि default check process exact browser endpoints को strict match करे।
---
<Link> vs <NavLink> में क्या अंतर है? (Comparison Table)
दोनों Components के behaviors को deep contrast में समझने के लिए, आइए इस performance properties comparison check table को देखते हैं:| Features / Properties | <Link> Component | <NavLink> Component |
|---|---|---|
| Primary Purpose | General element page jumps या simple navigation hyperlinks. | Navigation menu bars, sidebars, links highlights toggles. |
| Active Class Insertion | No (कोई automated style check injection नहीं होता) | Yes (Automatically injects active class name matches) |
| Dynamic Props Functionality | className attributes accept standard statically declared string. | Supports standard strings and JavaScript arrow functions ({ isActive }) => ... |
| Performance Metric | Slightly faster runtime comparison (no URL processing check overhead) | Marginal dynamic string comparisons internally process regular routing. |
| Match Restriction Prop | Not Applicable | Supports end prop behavior for absolute matching resolution. |
Complete Implementation Code (Production-Ready)
चलिए दोस्तों, अब सब कुछ मिलाकर एक functional working Navbar, CSS files और components structure code setup complete write-up देखते हैं ताकि आप इसे direct use कर सकें।1. Navbar.jsx Component
import { NavLink } from 'react-router-dom';
import './Navbar.css';
export default function Navbar() {
return (
<nav className="main-navbar">
<div className="nav-logo">
<h2>DevPortal</h2>
</div>
<ul className="nav-links">
<li>
<NavLink
to="/"
end
className={({ isActive }) => isActive ? "nav-item active-link" : "nav-item"}
>
Home
</NavLink>
</li>
<li>
<NavLink
to="/about"
className={({ isActive }) => isActive ? "nav-item active-link" : "nav-item"}
>
About
</NavLink>
</li>
<li>
<NavLink
to="/contact"
className={({ isActive }) => isActive ? "nav-item active-link" : "nav-item"}
>
Contact
</NavLink>
</li>
</ul>
</nav>
);
}
2. Navbar.css Stylesheet
इस CSS code को create कर अपने layout files path reference mappings से bind करें:.main-navbar {
display: flex;
justify-content: space-between;
align-items: center;
background-color: #0f172a;
padding: 15px 30px;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}
.nav-logo h2 {
color: #06b6d4;
margin: 0;
font-family: sans-serif;
}
.nav-links {
list-style: none;
display: flex;
gap: 20px;
margin: 0;
padding: 0;
}
.nav-item {
color: #94a3b8;
text-decoration: none;
font-size: 16px;
font-weight: 500;
padding: 8px 16px;
border-radius: 6px;
transition: all 0.3s ease;
}
.nav-item:hover {
color: #f8fafc;
background-color: #1e293b;
}
/* Active Class Dynamic Styles styling injected by NavLink */
.active-link {
color: #ffffff !important;
background-color: #06b6d4;
box-shadow: 0 4px 10px rgba(6, 182, 212, 0.3);
}
इस component architecture के flow parameters checks dynamic changes verify करने के लिए React App run करें (`npm run dev`)। आप देखेंगे कि route transitions instantaneous हैं, browser refresh wheel move नहीं करता, और static/active dynamic changes instantly style render attributes update process accurate display कर रहे हैं।
---
Common Routing Errors और उन्हें कैसे Fix करें?
जब developers React Router config build-out करते हैं, तो कुछ errors standard benchmarks में बार-बार आते हैं। चलिए देख लेते हैं कि उन्हें conceptual resolution mechanism से कैसे fix error stack handle करेंगे।1. "useHref() may be used only in the context of a <Router> component"
यह common runtime error तब आता है जब आप `Link` या `NavLink` component का use `BrowserRouter` components dynamic wrapper contextual boundaries के बाहर कर देते हैं। * Solution: Check करें कि क्या आपकी layout navigation files root files nested references (`App.jsx` setup) dynamic initialization sequence `BrowserRouter` के wrapper child tree hierarchy boundary limits के dynamic block elements bounds inside structure loop contain कर रही है। `BrowserRouter` को हमेशा highest setup levels level (`main.jsx`) पर configuration declare करें।2. Dynamic state updates missing components payload values
यदि navigation routes context values empty display process parameters data flow parameters errors catch correct attributes pass verify fail block return instances reflect runtime loops check:// Send details correctly object
<Link to="/profile" state={{ role: "admin", id: 2050 }}>Profile</Link>
Target routes dynamic file components load structures references variables state context fetch with `useLocation` react hook correctly sequence fetch verify template syntax check:
import { useLocation } from 'react-router-dom';
const Profile = () => {
const location = useLocation();
const dataReceived = location.state; // dynamically fetches: { role: "admin", id: 2050 }
return <div>Role: {dataReceived?.role}</div>;
};
---
React Router Performance Best Practices
- Code Splitting: Large component files bundles scale optimizations performance load decrease route components dynamic splits with lazy loads apply structures. Use `React.lazy()` configuration dynamically:
import { lazy, Suspense } from 'react'; const Home = lazy(() => import('./pages/Home')); - Prefetching: Users card item view transition triggers dynamic trigger events updates can mouse hover layouts preload optimization techniques trigger updates handles can boost web loading speeds!
- Relative Paths: Deep-nested sub-directory component structures require flexible matching dynamically. Use relative paths to write flexible navigation components. Official document guide specs rules patterns can be detailed from React Router Documentation.


टिप्पणियाँ
एक टिप्पणी भेजें