A
AiTechWorlds
AiTechWorlds
npm install react-router-dom// main.jsx / index.jsx
import { BrowserRouter } from 'react-router-dom';
import App from './App';
ReactDOM.createRoot(document.getElementById('root')).render(
<BrowserRouter>
<App />
</BrowserRouter>
);import { Routes, Route, Link, NavLink } from 'react-router-dom';
function App() {
return (
<>
<nav>
<NavLink to="/" end className={({ isActive }) => isActive ? 'active' : ''}>
Home
</NavLink>
<NavLink to="/about">About</NavLink>
<NavLink to="/blog">Blog</NavLink>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/blog" element={<Blog />} />
<Route path="*" element={<NotFound />} /> {/* 404 catch-all */}
</Routes>
</>
);
}<Route path="/blog/:slug" element={<BlogPost />} />
<Route path="/users/:userId/posts/:postId" element={<PostDetail />} />// BlogPost.jsx β access params
import { useParams } from 'react-router-dom';
function BlogPost() {
const { slug } = useParams();
// fetch post by slug...
return <article>{slug}</article>;
}// Nested layout pattern
function App() {
return (
<Routes>
<Route path="/dashboard" element={<DashboardLayout />}>
<Route index element={<DashboardHome />} /> {/* /dashboard */}
<Route path="analytics" element={<Analytics />} /> {/* /dashboard/analytics */}
<Route path="settings" element={<Settings />} /> {/* /dashboard/settings */}
</Route>
</Routes>
);
}
// DashboardLayout.jsx β renders child routes
import { Outlet } from 'react-router-dom';
function DashboardLayout() {
return (
<div className="dashboard">
<Sidebar />
<main>
<Outlet /> {/* child route renders here */}
</main>
</div>
);
}import { useNavigate, Link } from 'react-router-dom';
function LoginForm() {
const navigate = useNavigate();
async function handleSubmit(e) {
e.preventDefault();
await login(credentials);
navigate('/dashboard'); // redirect after login
navigate('/dashboard', { replace: true }); // replace history entry
navigate(-1); // go back
navigate(2); // go forward 2
}
return (
<form onSubmit={handleSubmit}>
{/* form fields */}
<Link to="/forgot-password">Forgot password?</Link>
</form>
);
}import { useSearchParams } from 'react-router-dom';
function ProductList() {
const [searchParams, setSearchParams] = useSearchParams();
const category = searchParams.get('category') ?? 'all';
const page = parseInt(searchParams.get('page') ?? '1', 10);
function setCategory(cat) {
setSearchParams(prev => {
prev.set('category', cat);
prev.set('page', '1');
return prev;
});
}
return (
<div>
<button onClick={() => setCategory('electronics')}>Electronics</button>
{/* URL becomes ?category=electronics&page=1 */}
</div>
);
}import { Navigate, Outlet } from 'react-router-dom';
import { useAuth } from './hooks/useAuth';
function ProtectedRoute() {
const { user } = useAuth();
return user ? <Outlet /> : <Navigate to="/login" replace />;
}
// Usage
function App() {
return (
<Routes>
<Route path="/login" element={<Login />} />
<Route element={<ProtectedRoute />}>
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/profile" element={<Profile />} />
</Route>
</Routes>
);
}import { useLocation } from 'react-router-dom';
function Component() {
const location = useLocation();
// location.pathname β "/users/42"
// location.search β "?tab=posts"
// location.hash β "#comments"
// location.state β data passed via navigate()
}
// Pass state through navigation
navigate('/login', { state: { from: location } });
// Read it in the destination
const location = useLocation();
const from = location.state?.from?.pathname ?? '/';
navigate(from, { replace: true });| Hook | Returns | Use Case |
|---|---|---|
useParams() | { slug, id, ... } | Dynamic route segments |
useNavigate() | navigate function | Programmatic navigation |
useLocation() | Location object | Current URL, state |
useSearchParams() | [searchParams, setSearchParams] | Query string |
useMatch(pattern) | Match object or null | Check if route matches |
useOutletContext() | Context from parent Outlet | Pass data down nested routes |
import { lazy, Suspense } from 'react';
import { Routes, Route } from 'react-router-dom';
const Home = lazy(() => import('./pages/Home'));
const Dashboard = lazy(() => import('./pages/Dashboard'));
const Analytics = lazy(() => import('./pages/Analytics'));
function App() {
return (
<Suspense fallback={<LoadingSpinner />}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/analytics" element={<Analytics />} />
</Routes>
</Suspense>
);
} instead of for internal navigation β causes full page reloadend prop on β / matches every route so it's always "active" inside a route without in the parent β children never render* catch-all route β unmatched paths show nothing instead of a 404 pagenavigate without replace: true after authentication redirects β leaves login page in browser historyAdvertisement
Get more notes like this daily on Telegram!
Free study notes, cheat sheets & AI tips
Last reviewed on June 13, 2026 by the AiTechWorlds Notes Team. Free cheat sheet β no signup required.
Advertisement
Join AiTechWorlds on Telegram and get daily AI tips, prompt engineering templates, coding resources, and exclusive content β 100% free!
No spam. Leave anytime.