Skip to content

Latest commit

 

History

History
107 lines (80 loc) · 3.86 KB

nested-routes.md

File metadata and controls

107 lines (80 loc) · 3.86 KB

Nested Routes: Structuring Your Application 📂

Welcome back! Today, we’re diving into nested routes, a powerful feature in React Router that allows you to build complex UI structures by nesting routes within routes. This is particularly useful for applications that have a hierarchical structure, such as dashboards or multi-page forms.

What Are Nested Routes?

Nested routes allow you to create a hierarchy of routes that can share layouts and components. This means you can define a parent route that includes child routes, enabling a more organized and manageable routing structure.

Example 1: Using BrowserRouter

Let’s imagine a simple blog application where we have a layout with a sidebar and main content area. The blog will have routes for the main page and specific blog posts.

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Layout from './Layout';
import Home from './Home';
import BlogPost from './BlogPost';
import NotFound from './NotFound';

const App = () => {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Layout />}>
          <Route index element={<Home />} />
          <Route path="post/:id" element={<BlogPost />} />
        </Route>
        <Route path="*" element={<NotFound />} />
      </Routes>
    </Router>
  );
};

export default App;

Explanation:

  • Layout Component: This is the parent component that includes common elements like the sidebar and header. It renders the children routes within it.
  • index Route: The index route renders the Home component when the user visits the base URL.
  • Dynamic Segment: The post/:id route captures the blog post ID, allowing us to display different posts based on the ID.

Mia: "So, the Layout component wraps around the Home and BlogPost components?"

Leo: "Exactly! This keeps our layout consistent and organized." 🗂️

Example 2: Using createBrowserRouter

With React Router v6.4 and later, you can use the createBrowserRouter function to set up routes more declaratively. Here’s how you can implement the same blog structure:

import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import Layout from './Layout';
import Home from './Home';
import BlogPost from './BlogPost';
import NotFound from './NotFound';

const router = createBrowserRouter([
  {
    path: '/',
    element: <Layout />,
    children: [
      {
        index: true,
        element: <Home />,
      },
      {
        path: 'post/:id',
        element: <BlogPost />,
      },
    ],
  },
  {
    path: '*',
    element: <NotFound />,
  },
]);

const App = () => {
  return <RouterProvider router={router} />;
};

export default App;

Explanation:

  • createBrowserRouter: This function helps define routes in a more structured way, encapsulating the routes in an array.
  • Children Routes: The children property defines nested routes under the parent route, similar to how it works with BrowserRouter.
  • RouterProvider: This component takes care of providing the router to your application.

Mia: "This seems more organized! What are the advantages?" Leo: "It indeed keeps the routing logic more clear and concise!" 🌟

Benefits of Nested Routes

  1. Cleaner Code: Grouping related routes makes your code easier to read and manage.
  2. Shared Layouts: You can define layouts that are shared across multiple routes, reducing duplication.
  3. Scalability: As your application grows, nested routes help maintain structure and clarity.

Fun Fact! 🎉

Did you know that you can nest routes to any level? This means you can have child routes within child routes, allowing for highly customizable and organized routing structures!

Navigation

Previous: navigate and useNavigate | Next: Route Parameters: Dynamic Routing