Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nested routing using protected routes is not working properly

earlier I posted a similar question: Method for checking admin is redirecting me to main page when trying to login

I tried to implement the protected route, inside a protectRoute.tsx:

import { Navigate, Outlet } from "react-router";
import { RootStateOrAny, useSelector } from "react-redux";

interface ProtectRouteProps {}

export default function ProtectRoute(props: ProtectRouteProps) {
  const userSignin = useSelector((state: RootStateOrAny) => state.userSignin);
  const { userInfo } = userSignin;

  return userInfo?.user?.isAdmin ? <Outlet /> : <Navigate to='/' />;
}

I don’t really know what ProtectRouteProps is and what I should put in it. Also in the routing part I did like he told me:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<Route path='/createItem' element={<ProtectRoute />} />
<Route path='/createItem' element={<CreateItem />} />

The problem now is that can’t access CreateItem because is going on the ProtectRoute page that is an empty one. What should i do?

>Solution :

I don’t really know what ProtectRouteProps is and what I should put in it.

There are no props. This is clear by the usage:

<Route path='/createItem' element={<ProtectRoute />} />

No props are passed to ProtectRoute. You can drop the props object:

import { Navigate, Outlet } from "react-router";
import { RootStateOrAny, useSelector } from "react-redux";

export default function ProtectRoute() {
  const userSignin = useSelector((state: RootStateOrAny) => state.userSignin);
  const { userInfo } = userSignin;

  return userInfo?.user?.isAdmin ? <Outlet /> : <Navigate to='/' replace />;
}

The problem now is that can’t access CreateItem because is going on
the ProtectRoute page that is an empty one. What should i do?

"Auth" routes are what are called layout routes. They apply some logic, perhaps some styled layout CSS, and render an Outlet for nested Route components to be rendered into. The nested Route components use the path prop for route matching.

Example:

<Route element={<ProtectRoute />}>
  <Route path='/createItem' element={<CreateItem />} />
  ... other protected routes ...
</Route>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading