React Router v6
Client-side routing — Route, Link, useNavigate, useParams, and nested routes
Skills taught: react.client-routing, react.react-router-v6, react.useNavigate, react.useParams, react.nested-routes
React Router v6 — in-browser simulation
Tip: The playground below simulates React Router using MemoryRouter (no actual URL changes) so it works in the iframe. In a real app, use BrowserRouter or HashRouter — the component API is identical.
// Real-app setup (outside playground)
import { BrowserRouter, Routes, Route, Link, useNavigate, useParams, NavLink, Outlet } from 'react-router-dom';
// Pages
function Home() {
return <h2>🏠 Home</h2>;
}
function About() {
return <h2>ℹ️ About Us</h2>;
}
function UserList() {
const navigate = useNavigate(); // programmatic navigation
const users = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];
return (
<div>
<h2>👥 Users</h2>
{users.map(u => (
<button key={u.id} onClick={() => navigate(`/users/${u.id}`)}>{u.name}</button>
))}
</div>
);
}
function UserDetail() {
const { id } = useParams(); // reads :id from the URL
return <h2>User #{id} detail page</h2>;
}
function NotFound() {
return <h2>404 — Not Found</h2>;
}
// Layout with shared Navbar
function Layout() {
return (
<>
<nav style={{ display: 'flex', gap: '12px', padding: '8px', background: '#1a1f2b' }}>
<NavLink to='/' style={({ isActive }) => ({ color: isActive ? '#4fd1c5' : '#fff' })}>Home</NavLink>
<NavLink to='/about' style={({ isActive }) => ({ color: isActive ? '#4fd1c5' : '#fff' })}>About</NavLink>
<NavLink to='/users' style={({ isActive }) => ({ color: isActive ? '#4fd1c5' : '#fff' })}>Users</NavLink>
</nav>
<main style={{ padding: '12px' }}>
<Outlet /> {/* matched child route renders here */}
</main>
</>
);
}
// App with nested routes
function App() {
return (
<BrowserRouter>
<Routes>
<Route path='/' element={<Layout />}>
<Route index element={<Home />} />
<Route path='about' element={<About />} />
<Route path='users' element={<UserList />} />
<Route path='users/:id' element={<UserDetail />} />
<Route path='*' element={<NotFound />} />
</Route>
</Routes>
</BrowserRouter>
);
}
Frequently Asked Questions
When do I use useNavigate vs Link?
Use Link (or NavLink) for clickable navigation elements in JSX — menus, buttons, text links. Use useNavigate for programmatic navigation triggered by events — after a form submits successfully, after an async operation completes, or when a condition is met. useNavigate gives you the navigate function: call navigate('/dashboard') or navigate(-1) to go back.