Redirect to login page in react router 4
15,677
I usually create a PrivateRoute
component that checks if the user is logged in (via prop, redux, localstorage or something).
Something like:
const PrivateRoute = ({ isLoggedIn, ...props }) =>
isLoggedIn
? <Route { ...props } />
: <Redirect to="/login" />
In the router I then use it for my, well, private routes :)
<Switch>
<PrivateRoute isLoggedIn={ this.state.loggedIn } path="/protected" component={Protected} />
<Route path="/login" component={Login}/>
</Switch>
Author by
Anshul Srivastava
Updated on June 14, 2022Comments
-
Anshul Srivastava almost 2 years
I am new to react and still learning my way around. I am creating a single page app where the user is redirected to the login page if he is not logged in. React has a Redirect component and I am not sure how to use it.
Following is my app.js :-
import React, { Component } from 'react'; import { Route, Switch, Redirect } from 'react-router-dom'; import Login from './components/login/login.js' import Protected from './components/protected/protected.js' import './App.css'; class App extends Component { state = { loggedIn: false // user is not logged in }; render() { return ( <Switch> <Route path="/protected" component={Protected}/> <Route path="/login" component={Login}/> </Switch> ); } } export default App;
In the above scenario, I want the user to be redirected to the
/login
page if the stateloggedIn
is false or else it should go to the/protected
page. -
zero_cool almost 5 yearshow do you pass the current value of isLoggedIn to the component if you have to dispatch an action to check the state - and that is async?
-
0xc14m1z almost 5 yearsYou can just connect the root component to redux. By default,
isLoggedIn
will befalse
. When you reach the login page and perform the login, it will be set totrue
.