A custom component that checks if user is loggedIn, otherwise it redirects to the login page
const ProtectedRoute = ({ component: Component, ...rest }) => {
const authenticated = true; // change this to your isLoggedIn state
return (
<Route {...rest} render={(props) => (
authenticated === true ?
<Component {...props} /> : <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
)} />
)
};
- Change the
authenticated
state to match your login state state: { from: props.location }
is used to return the user back to the page they were redirected from
Example Usage
<ProtectedRoute exact path='/dashboard' component={Dashboard} />
<Route exact path='/login' component={Login} />