Language: JavaScript
Routing
React Router was created by Ryan Florence and Michael Jackson in 2014 to solve the problem of handling navigation in single-page React applications. It provides declarative routing components, nested routes, and dynamic route matching, making it easier to manage application state and navigation.
React Router is a standard library for routing in React applications. It enables navigation among views, allows changing the browser URL, and keeps the UI in sync with the URL.
npm install react-router-domyarn add react-router-domReact Router uses components like `<BrowserRouter>`, `<Routes>`, `<Route>`, and `<Link>` to define routes and navigation. It supports dynamic route parameters, nested routes, redirects, and route guards.
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
function Home() { return <h1>Home</h1>; }
function About() { return <h1>About</h1>; }
function App() {
return (
<Router>
<nav>
<Link to='/'>Home</Link>
<Link to='/about'>About</Link>
</nav>
<Routes>
<Route path='/' element={<Home />} />
<Route path='/about' element={<About />} />
</Routes>
</Router>
);
}Sets up a basic router with two routes (`/` and `/about`) and links for navigation.
import { useParams } from 'react-router-dom';
function User() {
const { id } = useParams();
return <h1>User ID: {id}</h1>;
}
<Routes>
<Route path='/user/:id' element={<User />} />
</Routes>Demonstrates using dynamic route parameters with `useParams` hook.
function Dashboard() { return (
<div>
<h1>Dashboard</h1>
<Routes>
<Route path='stats' element={<Stats />} />
<Route path='settings' element={<Settings />} />
</Routes>
</div>
); }Shows how to define nested routes within a parent route.
import { Navigate } from 'react-router-dom';
<Route path='/old' element={<Navigate to='/new' replace />} />Redirects from `/old` to `/new` using the `Navigate` component.
function PrivateRoute({ children }) {
const isAuthenticated = false; // replace with auth logic
return isAuthenticated ? children : <Navigate to='/login' />;
}
<Routes>
<Route path='/dashboard' element={<PrivateRoute><Dashboard /></PrivateRoute>} />
</Routes>Demonstrates guarding routes based on authentication status.
Use `<BrowserRouter>` at the root of your app for client-side routing.
Keep route paths consistent and semantic for better readability and SEO.
Use `useParams`, `useLocation`, and `useNavigate` hooks for dynamic route handling.
Prefer nested routes for hierarchical UI structures.
Use `Navigate` for redirects and route guards.