Nested Routes in React Router
Key Concepts
- Nested Routes
- Parent and Child Routes
- Outlet Component
- Dynamic Nested Routes
- Nested Route Parameters
Nested Routes
Nested Routes allow you to create a hierarchical structure of routes within your application. This is useful for organizing complex applications with multiple levels of navigation.
Parent and Child Routes
In nested routing, you define a parent route that contains one or more child routes. The parent route renders a layout component, and the child routes render specific components within that layout.
Example:
<Routes> <Route path="/dashboard" element={<Dashboard />}> <Route path="profile" element={<Profile />} /> <Route path="settings" element={<Settings />} /> </Route> </Routes>
Outlet Component
The Outlet component is used in the parent route to render the child routes. It acts as a placeholder where the child route components will be rendered.
Example:
function Dashboard() { return ( <div> <h1>Dashboard</h1> <Outlet /> </div> ); }
Dynamic Nested Routes
Dynamic nested routes allow you to create routes that can change based on dynamic data, such as user IDs or product categories. This is achieved by using route parameters.
Example:
<Routes> <Route path="/users/:userId" element={<UserProfile />}> <Route path="posts" element={<UserPosts />} /> <Route path="settings" element={<UserSettings />} /> </Route> </Routes>
Nested Route Parameters
Nested route parameters allow you to pass dynamic values from the parent route to the child routes. This is useful for creating dynamic nested routes.
Example:
function UserProfile() { const { userId } = useParams(); return ( <div> <h1>User Profile: {userId}</h1> <Outlet /> </div> ); }
Analogies
Think of nested routes as a filing cabinet. The parent route is the main drawer, and the child routes are the folders inside that drawer. The Outlet component is like a placeholder in the drawer where the folders (child routes) can be placed.
Another analogy is a family tree. The parent route is like the grandparent, and the child routes are like the children and grandchildren. The Outlet component is like the space where the family members (child routes) gather.