Reputation: 1446
I am using react-redux for changing the state in my app.In my router page how can I route based on conditions.ie,If the user logged status is true then if i go to the login component it must redirect to the home component and the user logged status is false,if i go to the home component it must redirect to the login component.
routes.js
const routes=() => (
<Router>
<div>
<Header />
<Route exact path="/" render={ props => <div><FirstConnectedComponent /><SecondConnectedComponent /></div>} />
<Route path="/login" component={ requireAuth(Login) } />
<Route path="/register" component={ UserReg } />
<Route path="/home" component={ Home } />
<Footer />
</div>
</Router>
)
export default routes;
Upvotes: 2
Views: 876
Reputation: 483
How about creating a new route component called PrivateRoute
PrivateRoute.js
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
export const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
localStorage.getItem('authenticated')
? <Component {...props} />
: <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
)} />
)
index.js
First import it then use -
<PrivateRoute path="/" component={MyComponent} />
Upvotes: 1
Reputation: 2742
You can add a function call :
onEnter={this.requireAuth.bind(this)}
And the function could be something like this :
requireAuth(nextState, replace) {
if (this.user === undefined || this.user === null) {
replace('/login');
}
}
Upvotes: 0