Dynamic routing allows you to create routes that accept parameters, making your app more flexible and data-driven. React Router makes it easy to define and use these parameters for dynamic content.
Dynamic routes use parameters in the path, like /users/:id
, to render different content based on the URL. This is essential for user profiles, product pages, and any content that depends on an identifier.
/user/:id
).Here's how to define and use a dynamic route:
1import { BrowserRouter, Routes, Route, useParams } from "react-router-dom"; 2 3function UserProfile() { 4 const { id } = useParams(); 5 return <h2>User ID: {id}</h2>; 6} 7 8function App() { 9 return ( 10 <BrowserRouter> 11 <Routes> 12 <Route path="/user/:id" element={<UserProfile />} /> 13 </Routes> 14 </BrowserRouter> 15 ); 16}
/user/123
will render User ID: 123
.useParams()
gives you access to the route parameters.Nested routes allow you to render child components inside parent routes, making it easier to build complex layouts in React applications.
Nested routes let you define routes inside other routes. This is useful for dashboards, layouts, or any page with sub-sections. They help you organize your app and reflect its structure in the URL.
<Outlet />
to render child routes inside parent components.Here's how to set up nested routes:
1import { BrowserRouter, Routes, Route, Outlet, Link } from "react-router-dom"; 2 3function Dashboard() { 4 return ( 5 <div> 6 <h2>Dashboard</h2> 7 <nav> 8 <Link to="profile">Profile</Link> 9 <Link to="settings">Settings</Link> 10 </nav> 11 <Outlet /> 12 </div> 13 ); 14} 15 16function Profile() { 17 return <h3>Profile Page</h3>; 18} 19 20function Settings() { 21 return <h3>Settings Page</h3>; 22} 23 24function App() { 25 return ( 26 <BrowserRouter> 27 <Routes> 28 <Route path="dashboard" element={<Dashboard />}> 29 <Route path="profile" element={<Profile />} /> 30 <Route path="settings" element={<Settings />} /> 31 </Route> 32 </Routes> 33 </BrowserRouter> 34 ); 35}
<Outlet />
renders the matched child route.<Route>
elements define sub-pages.Dynamic routing lets you build flexible, data-driven pages in React. Use route parameters to display content based on the URL and provide a personalized user experience. Nested routes help you organize your React app and create layouts with multiple levels of navigation. Use them to keep your codebase clean and your navigation intuitive.