React18 - Routing 11 - Layout Routes - Auth'd login loses NavBar

I notice after refactoring the auth to use the Layouts and PrivateRoutes solution that when you switch back to an Authenticated user, the Routing takes you to the login page but drops the NavBar.

I added back Layout under PrivateRoutes and as a parent of UsersPage, and it seems to work, but is this a correct solution?

P.S. yes I’ve spotted and corrected my ‘PrivatRoutes.tsx’ typo

I noticed the same problem and at first did exactly the same. But I wondered how can I do this without repeating same code in two places and just passed PrivateRoutes component as a child of Layout, because that’s the place we have NavBar component.

import { createBrowserRouter } from "react-router-dom";
import HomePage from "./HomePage";
import UserDetail from "./UserDetail";
import Layout from "./Layout";
import UsersPage from "./UsersPage";
import ErrorPage from "./ErrorPage";
import LoginPage from "./LoginPage";
import PrivateRoutes from "./PrivateRoutes";

const router = createBrowserRouter([
    {
        path: "/",
        element: <Layout />,
        errorElement: <ErrorPage />,
        children: [
            { index: true, element: <HomePage /> },
            { path: "/login", element: <LoginPage /> },
            {
                element: <PrivateRoutes />,
                children: [
                    {
                        path: "users",
                        element: <UsersPage />,
                        children: [{ path: ":id", element: <UserDetail /> }],
                    },
                ],
            },
        ],
    },
]);

export default router;

You can also try to use createRoutesFromElements(). For me it’s easier to visualize what’s going on with routing using JSX instead of objects. Code below:

import {
    Route,
    createBrowserRouter,
    createRoutesFromElements,
} from "react-router-dom";
import HomePage from "./HomePage";
import UserDetail from "./UserDetail";
import Layout from "./Layout";
import UsersPage from "./UsersPage";
import ErrorPage from "./ErrorPage";
import LoginPage from "./LoginPage";
import PrivateRoutes from "./PrivateRoutes";

const router = createBrowserRouter(
    createRoutesFromElements(
        <Route path="/" element={<Layout />} errorElement={<ErrorPage />}>
            <Route index element={<HomePage />} />
            <Route path="login" element={<LoginPage />} />
            <Route element={<PrivateRoutes />}>
                <Route path="users" element={<UsersPage />}>
                    <Route path=":id" element={<UserDetail />} />
                </Route>
            </Route>
        </Route>
    )
);

export default router;