import React, { useContext } from "react";
import { AuthContext } from "../context/auth";
import { Navigate, useLocation } from "react-router-dom";
const PrivateRoute = ({ component }) => {
const { user } = useContext(AuthContext);
let location = useLocation()
if (!user) {
return <Navigate to='/login' state={{ from: location }} />
};
return (component);
};
export const PublicRoute = ({ component }) => {
const { user } = useContext(AuthContext);
if (!user) {
return (component);
};
return <Navigate to='/dashboard' />
};
export default PrivateRoute;
<Routes>
<Route exact path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route
path='/register'
element={<PublicRoute><Register /></PublicRoute>}
/>
<Route
exact
path='/login'
element={<PublicRoute><Login /></PublicRoute>}
/>
<Route
exact
path='/dashboard'
element={<PrivateRoute><Dashboard /></PrivateRoute>}
/>
</Routes>
I tried to prevent users who are already logged in from accessing the register or login page and it worked but now after logging out I am not able to access login and register pages.
2
Answers
I was just trying random stuff and it started working i would still like an explanation if possible.
these were the changes i made
The route guards aren’t passed any
component
prop. You likely meant to use the implicitchildren
prop.