Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating Root Route View after Nesting Routes with React Router

I have created an app that has a dashboard path and then some nested routes. I want my root dashboard path to display the main dashboard view and then the nested routes to simply display whatever element they have set.

<Route
  path="dashboard"
  element={
    <PrivateRoute>
      <ModalProvider>
        <Dashboard />
      </ModalProvider>
    </PrivateRoute>
  }
>
  <Route path="settings" element={<Account />} />
  <Route path="pets" element={<Pets />} />
  <Route path="calendar" element={<Calendar />} />
  <Route
    path="calculator"
    element={
      <CalculatorProvider>
        <Calculator />
      </CalculatorProvider>
    }
  />
</Route>

but it seems like I can not just add the main dashboard view in the Dashboard component because then of course whatever is in that component displays for every nested route. How can I have the route path ‘dashboard’ display its own component?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If I understand the question correctly, you want the <Dashboard /> component to render on "/dashboard" while the other component render on "/dashboard/settings" etc. Render the <Dashboard /> on an index route.

Example:

const DashboardLayout = () => (
  <PrivateRoute>
    <ModalProvider>
      <Outlet />
    </ModalProvider>
  </PrivateRoute>
);

<Route path="dashboard" element={<DashboardLayout />}>
  <Route index element={<Dashboard />} />          // "/dashboard"
  <Route path="settings" element={<Account />} />  // "/dashboard/settings"
  <Route path="pets" element={<Pets />} />         // "/dashboard/pets"
  <Route path="calendar" element={<Calendar />} /> // "/dashboard/calendar"
  <Route
    path="calculator"                              // "/dashboard/calculator"
    element={
      <CalculatorProvider>
        <Calculator />
      </CalculatorProvider>
    }
  />
</Route>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading