I had a similar question but this time the problem is a bit different. So I have an authorization component "Login". And when the user logs in it should redirect to the home page. Otherwise if there isn't any user logged in, it redirect to the login page.
My PrivateRoute.jsx
looks like this:
const PrivateRoute = ({component: Component, ...rest}) => {
const { user } = useContext(AuthContext);
const navigate = useNavigate();
return (
<Route
{...rest}
exact
render={(props => user ? <Component {...props}/> : <Navigate replace to="/login" />)}
/>
)
}
So as you see it accepts props
and also the user.
And my App.js:
function App() {
return (
<AuthProvider>
<BrowserRouter>
<Navbar/>
<Routes>
<Route exact path="/register" element={<Register/>}/>
<Route exact path="/login" element={<Login/>}/>
<PrivateRoute exact path="/" element={<Home/>}/>
</Routes>
</BrowserRouter>
</AuthProvider>
);
}
So as you see I added PrivateRoute
along with other routes, but for some reason I have an error:
[PrivateRoute] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>
So I closed the PrivateRoute
like this:
<>
<PrivateRoute exact path="/" element={<Home/>}/>
</>
But it doesn't solve the problem. I need to redirect to the Login
page if the user isn't logged in and to the Home
is he's logged in.