0

I am trying to add a private route with the use routes hook in my react project. How can I add a private route with the use routes hook in react project?

Atik Hasan
  • 11
  • 2
  • Does this answer your question? [Protected route with react router v6](https://stackoverflow.com/questions/62384395/protected-route-with-react-router-v6) – Victor Orlyk Jun 06 '22 at 16:28
  • What have you tried? We can't help resolve issues with code we can't see. https://stackoverflow.com/help/minimal-reproducible-example – Drew Reese Jun 06 '22 at 16:29

2 Answers2

1
// output routes
const AppRouter = observer(() => {
  const { user } = useContext(Context); // get information from Context
  const isAuth = user.isAuth;
  const isAdmin = user.user?.role === "ADMIN";
  const pages = useRoutes(routes(isAuth, isAdmin));
  return <Container>{pages}</Container>;
});

// routes
const routes = (isAuth, isAdmin) => {
  const publicRoutes = [
    {
      path: "/",
      element: <Navigate to={COURSE_CATALOG_FULL_ROUTE} replace />,
    },
    {
      path: COURSE_ROUTE,
      element: <CoursesPage />,
      children: [
        {
          path: "",
          element: <Navigate to={COURSE_CATALOG_FULL_ROUTE} replace />,
        },
        { path: COURSE_CATALOG_ROUTE, element: <CourseCatalogPage /> },
        {
          path: COURSE_ROUTE + ":id",
          element: <CoursePage />,
        },
      ],
    },
    {
      path: "*",
      element: <NotFound />,
    },
  ];

  const authRoutes = [
    {
      path: MY_COURSES_ROUTE,
      element: isAuth ? <MyCoursesPage /> : <Navigate to={"/login"} replace />,
    },
    {
      path: CHOISE_COURSES_ROUTE,
      element: isAuth ? <ChoiseCoursesPage /> : <Navigate to={"/login"} replace />,
    },
    {
      path: ACCOUNT_ROUTE,
      element: isAuth ? <AccountPage /> : <Navigate to={"/login"} replace />,
    },
  ];

  const authAdminRoutes = [
    {
      path: ADMIN_ROUTE,
      element: isAdmin ? <AdminPage /> : <NotAccess />,
    },
    {
      path: ADMIN_COURSES_ROUTE,
      element: isAdmin ? <UnmoderCoursesPage /> : <NotAccess />,
    },
  ];
  return [...publicRoutes, ...authRoutes, ...authAdminRoutes];
};
OneIvan
  • 11
  • 2
-1

here

let element = useRoutes([
    {path: '/', element: isLoggedIn? <Home />: <Navigate to="/login" /> },
    {path: '/about', element: <About />},
  ]);
Victor Orlyk
  • 1,454
  • 2
  • 15
  • 27