~/
hackweb.dev
React Router
Quiz
⌘K
...
~/
/tutorials
/react/react-router/edit
~ Contribute
Suggest a correction or improvement. The author reviews it before it goes live.
Loading...
Comment
0 / 300
Typo
Grammar
Broken link
Clarify
Code
en/tutorials/react/15react-router
Write
Preview
Diff
# React Router React Router enables client-side navigation in single-page applications. ## Setting Up Routes ```jsx import { BrowserRouter, Routes, Route, Link } from "react-router-dom"; function App() { return ( <BrowserRouter> <nav> <Link to="/">Home</Link> <Link to="/about">About</Link> </nav> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> </Routes> </BrowserRouter> ); } ``` ## Dynamic Segments Use parameters in the URL: ```jsx <Route path="/users/:id" element={<UserProfile />} /> function UserProfile() { const { id } = useParams(); return <h1>User {id}</h1>; } ``` ## Navigating Programmatically ```jsx import { useNavigate } from "react-router-dom"; function LoginButton() { const navigate = useNavigate(); const handleLogin = async () => { await loginUser(); navigate("/dashboard"); }; return <button onClick={handleLogin}>Login</button>; } ``` ## Nested Routes ```jsx <Route path="/dashboard" element={<Dashboard />}> <Route path="profile" element={<Profile />} /> <Route path="settings" element={<Settings />} /> </Route> function Dashboard() { return ( <div> <h1>Dashboard</h1> <Outlet /> </div> ); } ``` ## Best Practices 1. Keep route definitions in one place 2. Use `Link` instead of `<a>` tags for navigation 3. Use nested routes for related pages 4. Handle 404 with a catch-all route (`path="*"`) ## Common Mistakes 1. Using `<a>` tags causes full page reloads 2. Forgetting to wrap with `BrowserRouter` 3. Not using `key` on dynamic routes when switching 4. Missing `Outlet` in parent routes breaks nesting
No changes yet
Reset to original
Submit suggestion
cancel