I’m trying to implement private and public routing in my project. But it isn’t working. I’m following the latest approach.I tried alot but can’t figure out the solution.
Signin is comes in public Routes. And PageLayout and its childrens comes in private Route. In future, i will add roles too.
Index.js:
const router = createBrowserRouter([
{
path: "/signin",
element: <Signin />,
},
{
path: "/",
element: <PrivateRoute isAuth={true} element={<PageLayout />} />,
errorElement: <ErrorPage />,
children: [
{
index: true,
element: <Dashboard />,
},
{
path: "dashboard",
element: <Dashboard />,
},
{
path: "doctors",
element: <DoctorsPage />,
},
{
path: "adddoctor",
element: <AddDoctorPage />,
},
])
PrivateRoute.js:
const PrivateRoute = ({ element: Element, isAuth, ...rest }) => {
const navigate = useNavigate();
useEffect(() => {
if (!isAuth) {
navigate("/signin", { replace: true });
}
}, [isAuth, navigate]);
return isAuth ? <Route {...rest} element={<Element />} /> : null;
};
export default PrivateRoute;
2
Answers
I noticed one error on the code: in
PrivateRoutes.js
, you need to use<Outlet />
fromreact-router-dom
instead of<Route />
:It should work once this is fixed. I troubleshot this here: https://codesandbox.io/s/naughty-nobel-pphwjx?file=/src/index.js
You can refer to their documentation here: https://reactrouter.com/en/main/start/tutorial