In the first part of our guide, we covered the basics of React Router, including setting up routes, navigation with Link
and NavLink
, and defining the routing structure using Routes
and Route
. In this second part, we’ll dive deeper into advanced features like nested routes, dynamic routing, and the Outlet component. These concepts allow you to build more complex and hierarchical navigation systems.
1. Nested Routing
What is Nested Routing?
In React Router, you can nest routes to create a hierarchy. This is useful when you want to organize pages that have subpages or when different sections of your application share a common layout. For example, a dashboard with subpages for profile and settings.
Example: Nested Routing
Here’s how you can implement nested routing:
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Dashboard from "./Dashboard";
import Profile from "./Profile";
import Settings from "./Settings";
function App() {
return (
<BrowserRouter>
<Routes>
{/* Parent Route */}
<Route path="dashboard" element={<Dashboard />}>
{/* Child Routes */}
<Route path="profile" element={<Profile />} />
<Route path="settings" element={<Settings />} />
</Route>
</Routes>
</BrowserRouter>
);
}
export default App;
Key Points
-
path="dashboard"
:- The parent route matches
/dashboard
and renders theDashboard
component.
- The parent route matches
-
path="profile"
andpath="settings"
:- These are child routes, nested under
/dashboard
. - They match
/dashboard/profile
and/dashboard/settings
.
- These are child routes, nested under
Output
- Navigating to
/dashboard
renders theDashboard
component. - Navigating to
/dashboard/profile
renders theProfile
component inside theDashboard
. - Navigating to
/dashboard/settings
renders theSettings
component inside theDashboard
.
2. The Outlet Component
What is Outlet?
The Outlet
component acts as a placeholder for child routes in a parent component. When a child route is matched, React Router will render the corresponding component inside the Outlet
of its parent.
Why Use Outlet?
Imagine a layout where the Dashboard
component has a common structure, like a sidebar or a header, and you want to render different child components (Profile
, Settings
) inside it. Instead of manually handling this, you can use the Outlet
component.
Example: Using Outlet
In the parent component (e.g., Dashboard
), include the Outlet
:
import { Outlet } from "react-router-dom";
function Dashboard() {
return (
<div>
<h1>Dashboard</h1>
<nav>
<a href="/dashboard/profile">Profile</a>
<a href="/dashboard/settings">Settings</a>
</nav>
<Outlet /> {/* Renders the child route component */}
</div>
);
}
export default Dashboard;
Complete Example: Parent and Child Routes
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Dashboard from "./Dashboard";
import Profile from "./Profile";
import Settings from "./Settings";
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="dashboard" element={<Dashboard />}>
<Route path="profile" element={<Profile />} />
<Route path="settings" element={<Settings />} />
</Route>
</Routes>
</BrowserRouter>
);
}
In this example:
- Navigating to
/dashboard/profile
rendersProfile
inside theDashboard
. - Navigating to
/dashboard/settings
rendersSettings
inside theDashboard
.
3. Dynamic Routing with Parameters
What is Dynamic Routing?
Dynamic routes allow you to define routes that can accept parameters in the URL. These parameters can be accessed in your component, enabling features like viewing a user’s profile or displaying specific content based on the ID in the URL.
Defining a Dynamic Route
Dynamic parameters are defined in the route path using a colon (:
), followed by the parameter name.
Example:
import { BrowserRouter, Routes, Route, useParams } from "react-router-dom";
function User() {
// Access the parameter using useParams
const { userId } = useParams();
return <h1>User ID: {userId}</h1>;
}
function App() {
return (
<BrowserRouter>
<Routes>
{/* Dynamic Route */}
<Route path="/user/:userId" element={<User />} />
</Routes>
</BrowserRouter>
);
}
export default App;
How it Works
-
path="/user/:userId"
:- The
:userId
defines a dynamic parameter.
- The
-
useParams()
:- A hook provided by React Router to access route parameters.
- It returns an object containing all the parameters in the current route.
Example Usage
If you navigate to /user/42
, the User
component renders:
User ID: 42
Here:
-
42
is the value of theuserId
parameter. - You can use
userId
in the component to fetch user-specific data or display it dynamically.
Multiple Parameters
You can define multiple parameters in a route:
<Route path="/product/:productId/review/:reviewId" element={<ProductReview />} />
Access them using useParams
:
function ProductReview() {
const { productId, reviewId } = useParams();
return (
<div>
<h1>Product ID: {productId}</h1>
<h1>Review ID: {reviewId}</h1>
</div>
);
}
Navigating to /product/123/review/456
renders:
Product ID: 123
Review ID: 456
Combining Nested and Dynamic Routes
You can use nested routes with dynamic parameters for even more flexibility.
Example: Nested Dynamic Routes
import { BrowserRouter, Routes, Route, useParams } from "react-router-dom";
function Product() {
const { productId } = useParams();
return (
<div>
<h1>Product ID: {productId}</h1>
<Outlet />
</div>
);
}
function ProductReview() {
const { reviewId } = useParams();
return <h2>Review ID: {reviewId}</h2>;
}
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="product/:productId" element={<Product />}>
<Route path="review/:reviewId" element={<ProductReview />} />
</Route>
</Routes>
</BrowserRouter>
);
}
export default App;
How It Works
- Navigate to
/product/123
:- Renders
Product
component withProduct ID: 123
.
- Renders
- Navigate to
/product/123/review/456
:- Renders
Product
component withProduct ID: 123
. - Inside it, renders
ProductReview
withReview ID: 456
.
- Renders
Summary
In this part, we covered advanced React Router concepts, including:
-
Nested Routes:
- Structuring routes hierarchically for better organization.
- Using the
Outlet
component to render child routes dynamically.
-
Dynamic Routes:
- Capturing and using URL parameters with
useParams
. - Creating flexible and reusable routes for dynamic content.
- Capturing and using URL parameters with
-
Combining Nested and Dynamic Routes:
- Building complex navigation systems with both nested and dynamic routing.
In the next part of the guide, we’ll explore:
- Redirects and navigation
- Protected routes
- Programmatic navigation
Stay tuned for the final installment of the Ultimate Guide to React Router series! 🚀
Top comments (0)