React Router
Navigation and routing for React applications
🧭 What is React Router?
React Router enables navigation between different pages in your React application without page reloads. It creates a single-page application experience with multiple views, managing URL changes and browser history seamlessly.
import { BrowserRouter, Routes, Route } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
);
}
Key Router Concepts
BrowserRouter
Wraps your app to enable routing
<BrowserRouter>
<App />
</BrowserRouter>
Routes & Route
Define paths and components
<Routes>
<Route path="/" element={<Home />} />
</Routes>
Link
Navigate without page reload
<Link to="/about">
About
</Link>
useNavigate
Programmatic navigation
const navigate = useNavigate();
navigate('/home');
🔹 Installing React Router
React Router DOM is the standard routing library for React web applications. It provides declarative routing components that integrate seamlessly with React's component model, enabling dynamic navigation and URL management.
# Install React Router
npm install react-router-dom
# or with yarn
yarn add react-router-dom
Note: Use react-router-dom for web applications and react-router-native for React Native.
🔹 Basic Routing Setup
Setting up basic routing involves wrapping your app with BrowserRouter and defining routes. Each route maps a URL path to a specific component, creating a multi-page experience within a single-page application.
// App.jsx
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';
import Contact from './pages/Contact';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</BrowserRouter>
);
}
export default App;
// pages/Home.jsx
function Home() {
return (
<div>
<h1>Home Page</h1>
<p>Welcome to the home page!</p>
</div>
);
}
export default Home;
🔹 Navigation with Link
The Link component creates clickable navigation without full page reloads. It's the React Router equivalent of anchor tags, providing smooth client-side navigation while maintaining browser history and back button functionality.
// Navbar.jsx
import { Link } from 'react-router-dom';
function Navbar() {
return (
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
</nav>
);
}
export default Navbar;
// App.jsx with Navbar
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Navbar from './components/Navbar';
import Home from './pages/Home';
import About from './pages/About';
function App() {
return (
<BrowserRouter>
<Navbar />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
);
}
🔹 Dynamic Routes with Parameters
URL parameters allow you to create dynamic routes that respond to different values. Use useParams hook to access these values, perfect for displaying specific items like user profiles or product details.
// App.jsx
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import UserProfile from './pages/UserProfile';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/user/:id" element={<UserProfile />} />
</Routes>
</BrowserRouter>
);
}
// pages/UserProfile.jsx
import { useParams } from 'react-router-dom';
function UserProfile() {
const { id } = useParams();
return (
<div>
<h1>User Profile</h1>
<p>Viewing profile for user ID: {id}</p>
</div>
);
}
export default UserProfile;
// Usage with Link
<Link to="/user/123">View User 123</Link>
<Link to="/user/456">View User 456</Link>
🔹 Programmatic Navigation
The useNavigate hook enables navigation through JavaScript code rather than user clicks. This is essential for redirecting after form submissions, authentication, or any programmatic flow control in your application.
// LoginForm.jsx
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
function LoginForm() {
const [username, setUsername] = useState('');
const navigate = useNavigate();
const handleSubmit = (e) => {
e.preventDefault();
// After successful login
if (username) {
navigate('/dashboard');
}
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="Username"
/>
<button type="submit">Login</button>
</form>
);
}
export default LoginForm;
// Navigate with options
const navigate = useNavigate();
// Go to a path
navigate('/home');
// Go back
navigate(-1);
// Go forward
navigate(1);
// Replace current entry
navigate('/home', { replace: true });
🔹 Nested Routes
Nested routes create hierarchical page structures with shared layouts. Parent routes can render common elements like headers, while child routes display specific content, perfect for dashboard layouts or multi-level navigation.
// App.jsx
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Dashboard from './pages/Dashboard';
import Profile from './pages/Profile';
import Settings from './pages/Settings';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/dashboard" element={<Dashboard />}>
<Route path="profile" element={<Profile />} />
<Route path="settings" element={<Settings />} />
</Route>
</Routes>
</BrowserRouter>
);
}
// pages/Dashboard.jsx
import { Outlet, Link } from 'react-router-dom';
function Dashboard() {
return (
<div>
<h1>Dashboard</h1>
<nav>
<Link to="profile">Profile</Link>
<Link to="settings">Settings</Link>
</nav>
{/* Child routes render here */}
<Outlet />
</div>
);
}
export default Dashboard;
🔹 404 Not Found Page
A catch-all route handles invalid URLs gracefully by displaying a 404 page. Use the asterisk path to match any unmatched routes, providing users with helpful feedback when they navigate to non-existent pages.
// App.jsx
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import NotFound from './pages/NotFound';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
{/* Catch all unmatched routes */}
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
);
}
// pages/NotFound.jsx
import { Link } from 'react-router-dom';
function NotFound() {
return (
<div>
<h1>404 - Page Not Found</h1>
<p>The page you're looking for doesn't exist.</p>
<Link to="/">Go back to Home</Link>
</div>
);
}
export default NotFound;