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?
Asked
Active
Viewed 1,135 times
0
-
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 Answers
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
-
2. Can you provide some more explanation on what does your code do? – Mr.SwiftOak Jun 08 '22 at 09:04
-1
here
let element = useRoutes([
{path: '/', element: isLoggedIn? <Home />: <Navigate to="/login" /> },
{path: '/about', element: <About />},
]);

Victor Orlyk
- 1,454
- 2
- 15
- 27