Advanced Concepts of React Router(Part 2)

harshm03

Harsh Mishra

Posted on November 13, 2024

Advanced Concepts of React Router(Part 2)

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;
Enter fullscreen mode Exit fullscreen mode

Key Points

  1. path="dashboard":
    • The parent route matches /dashboard and renders the Dashboard component.
  2. path="profile" and path="settings":
    • These are child routes, nested under /dashboard.
    • They match /dashboard/profile and /dashboard/settings.

Output

  • Navigating to /dashboard renders the Dashboard component.
  • Navigating to /dashboard/profile renders the Profile component inside the Dashboard.
  • Navigating to /dashboard/settings renders the Settings component inside the Dashboard.

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;
Enter fullscreen mode Exit fullscreen mode

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>
    );
}
Enter fullscreen mode Exit fullscreen mode

In this example:

  • Navigating to /dashboard/profile renders Profile inside the Dashboard.
  • Navigating to /dashboard/settings renders Settings inside the Dashboard.

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;
Enter fullscreen mode Exit fullscreen mode

How it Works

  1. path="/user/:userId":
    • The :userId defines a dynamic parameter.
  2. 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
Enter fullscreen mode Exit fullscreen mode

Here:

  • 42 is the value of the userId 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 />} />
Enter fullscreen mode Exit fullscreen mode

Access them using useParams:

function ProductReview() {
    const { productId, reviewId } = useParams();
    return (
        <div>
            <h1>Product ID: {productId}</h1>
            <h1>Review ID: {reviewId}</h1>
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode

Navigating to /product/123/review/456 renders:

Product ID: 123
Review ID: 456
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

How It Works

  1. Navigate to /product/123:
    • Renders Product component with Product ID: 123.
  2. Navigate to /product/123/review/456:
    • Renders Product component with Product ID: 123.
    • Inside it, renders ProductReview with Review ID: 456.

Summary

In this part, we covered advanced React Router concepts, including:

  1. Nested Routes:
    • Structuring routes hierarchically for better organization.
    • Using the Outlet component to render child routes dynamically.
  2. Dynamic Routes:
    • Capturing and using URL parameters with useParams.
    • Creating flexible and reusable routes for dynamic content.
  3. 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! 🚀

💖 💪 🙅 🚩
harshm03
Harsh Mishra

Posted on November 13, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related