Routing
The mechanism in single-page applications (SPAs) that maps URLs to specific views or components, enabling navigation without full page reloads.
Overview
Client-side routing allows SPAs to handle navigation and URL changes within the browser without requesting new HTML from the server. Routing libraries like React Router, Vue Router, and Angular Router provide declarative ways to define routes and navigate between different views while maintaining browser history and deep linking.
Example
javascript// React Router example import { BrowserRouter, Routes, Route, Link } from 'react-router-dom'; function App() { return ( <BrowserRouter> <nav> <Link to="/">Home</Link> <Link to="/about">About</Link> <Link to="/users/123">User Profile</Link> </nav> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="/users/:id" element={<UserProfile />} /> <Route path="*" element={<NotFound />} /> </Routes> </BrowserRouter> ); } // Access route parameters function UserProfile() { const { id } = useParams(); return <div>User ID: {id}</div>; } // Programmatic navigation import { useNavigate } from 'react-router-dom'; function LoginButton() { const navigate = useNavigate(); const handleLogin = () => { // After login logic navigate('/dashboard'); }; return <button onClick={handleLogin}>Login</button>; } // Protected routes function ProtectedRoute({ children }) { const isAuthenticated = useAuth(); return isAuthenticated ? children : <Navigate to="/login" />; }
Key Points
- Enables SPA navigation without page reload
- Maps URLs to components/views
- Maintains browser history
- Supports dynamic route parameters
- Common libraries: React Router, Vue Router
Learn More
- Component - React components
- React - React library
- React Router Docs