React Router 6 Nest Routes

Viewed 40

I have a protected route that wraps my layout route for my other components that uses the layout component.

Im having an issue with the protected route not working as expected. If a user is null, when i try to access localhost:3000/create for example it should render my landing page but instead i get a blank screen.

I realised if i only have one route that contains one element prop it works fine. What am i doing wrong?

My Routes

<Router>
  <Routes>
    <Route path='/' element={<LandingPage />} />
    <Route path='*' element={<NotFound />} />
    <Route element={<ProtectedRoutes />}>
      <Route element={<ResponsiveDrawer />}>
        <Route path='/dashboard' element={<Dashboard />} />
        <Route path='/create' element={<Create />} />
        <Route path='/edit/:id' element={<Edit />} />
      </Route>
    </Route>
  </Routes>
</Router>

My Protected Routes

const ProtectedRoutes = () => {
 const { user } = useContext(UserContext);
 // console.log(user);

 return user !== null ? <Outlet /> : <LandingPage />;
};
1 Answers

The ProtectedRoutes is rendering an Outlet component for nested Route components to be rendered into. The ResponsiveDrawer also needs to render an Outlet for any nested Route components it is wrapping.

<Router>
  <Routes>
    <Route path='/' element={<LandingPage />} />
    <Route path='*' element={<NotFound />} />
    <Route element={<ProtectedRoutes />}>    // <-- render Outlet
      <Route element={<ResponsiveDrawer />}> // <-- render Outlet
        <Route path='/dashboard' element={<Dashboard />} />
        <Route path='/create' element={<Create />} />
        <Route path='/edit/:id' element={<Edit />} />
      </Route>
    </Route>
  </Routes>
</Router>

The route rendering the ResponsiveDrawer is rendered into the ProtectedRoutes component's Outlet, and nested routes are rendered into the ResponsiveDrawer component's Outlet.

Example ResponsiveDrawer:

const ResponsiveDrawer = () => {
  // business logic

  return (
    <>
      {/* UI */}
      {/* Drawer UI */}
      <Outlet /> // <-- nested routes render here
    </>
  );
};
Related