Search code examples
reactjsreact-routerreact-router-dom

React router dom layout hides content


I have a project using react-router-dom, and I can't achieve to have a route in which I have a lateral menu.

I need my lateral menu to be available on each /users/:id routes, so I can navigate between differents informations about the current user.

This is what I came to :

            <Route path=":id" element={<UserLayout />}>
              <Route
                index
                element={
                  isLoading ? (
                    ""
                  ) : hasPermissionToRoute("/users/:id/") ? (
                    <User />
                  ) : (
                    <AccessForbidden />
                  )
                }
              />
              <Route
                path="contracts"
                element={
                  isLoading ? (
                    ""
                  ) : hasPermissionToRoute("/users/:id/contracts") ? (
                    "contracts"
                  ) : (
                    <AccessForbidden />
                  )
                }
              />
            </Route>

And <UserLayout /> being :

export function UserLayout({ children }) {
  return (
    <div className="flex gap-5">
      <div>menu</div>
      <div>{children}</div>
    </div>
  );
}

When I go to /users/id/ I only got menu displayed, same for /users/id/contracts. The problem is not coming from the conditions of the subroutes since when I delete element={<UserLayout />} it works properly (but without the lateral menu).

Any help would be greatly appreciated !


Solution

  • Add the Outlet component on your UserLayout component. Outlet component renders the matching child route with its respective component (here User)

    import { Outlet } from 'react-router-dom';
    
    export function UserLayout({ children }) {
      return (
        <div className="flex gap-5">
          <div>menu</div>
          <Outlet/>
        </div>
      );
    }