0

There is a public and private part of the app. An unauthenticated user shouldn't have access to the content rendered on private routes, and instead be presented with an error page.

The user should also be presented with an error page when trying to access a non existing route. This error page needs to be rendered as a child component to either LandingLayout or AppLayout, depending on the auth state, which is why I am not using the errorElement prop.

Here is the index.jsx where the router paths are defined:

const router = createBrowserRouter([
{
    path: "/",
    element: <ProtectedRouting UnAuthElement={<LandingLayout />} AuthElement={<AppLayout />} />,
    children: [
        { path: "/", element: <ProtectedRouting UnAuthElement={<LandingPage />} AuthElement={<PrivateHome />} /> },
        { path: "/createEvent", element: <ProtectedRouting AuthElement={<CreateEvent />} /> },
        { path: "/events", element: <ProtectedRouting AuthElement={<EventsPage />} /> },
        { path: "/contacts", element: <ProtectedRouting AuthElement={<ContactsPage />} /> },
        { path: "/notifications", element: <ProtectedRouting AuthElement={<Notifications />} /> },
        { path: "/weather", element: <ProtectedRouting AuthElement={<WeatherPage />} /> },
        {
            path: "/events/:eventId",
            element: <ProtectedRouting AuthElement={<SingleEventPage />} />,
        },
        { path: "/views", element: <ProtectedRouting AuthElement={<ViewsPage />} /> },
        { path: "/views/upload", element: <ProtectedRouting AuthElement={<UploadPhoto />} /> },
        {
            path: "/*",
            element: (
                <ErrorPage
                    title="Resource not found"
                    message="Make sure to enter a valid URL"
                />
            ),
        },
    ],
},

]);

Here is the ProtectedRouting component:

export const ProtectedRouting = ({
    UnAuthElement = <ErrorPage message="You must be logged in to access this page!" />,
    AuthElement,
}) => {
    const [user, loading] = useAuthState(auth);

    if (loading) {
        return <CustomSpinner />;
    }

    return user ? AuthElement : UnAuthElement;
};

This is the solution I came up with, and it works, but I am sure it can be improved, and probably simplified. I just couldn't find any resources that were suited to my case.

kokiqn
  • 1
  • 1

0 Answers0