1

I have code as follows. I'm using react-router-dom 6.6.1:

const App = () => {
  return <RouterProvider router={router} />;
};

Then the router is as follows:

const router = createBrowserRouter([
  {
    path: "/",
    element: <Protected />,
    children: [
      {
        path: routes.HOME,
        element: <Root />,
      },
      {
        path: routes.SETTINGS,
        element: <Settings />,
      }
    ]
  },
  {
    path: routes.FORGOT_PASSWORD,
    element: <ForgotPassword />,
  },
  {
    path: routes.LOGIN,
    element: <Login />,
  },


  {
    path: "*",
    element: <NotFound />,
  },

]);

Thus I want to have multiple routes which are protected (you can access them only if you are logged in), and I want to have multiple routes which are available for everybody (you do not need to be logged in)

But when I try to access routes.FORGOT_PASSWORD it redirects me to routes.LOGIN because of Protected.

In Protected I have:

import React from "react";
import {Outlet, Navigate, useLocation} from "react-router-dom";
import {routes} from "src/routes/routes";
import {useLocalStorage} from "src/hooks/useLocaleStorage";
import {useTranslation} from "react-i18next";

export default function Protected() {
    const {getFromStorage} = useLocalStorage();

    const isAuthenticated = getFromStorage('user')?.isAuthenticated;

    return isAuthenticated ? <Outlet/> : <Navigate to={routes.LOGIN}/>;
}

Why is that?

Boky
  • 11,554
  • 28
  • 93
  • 163

0 Answers0