I have a web site, and right now whether I’m logged or not, when I go to the root it shows my log in form. What I want is that if I’m logged and got to /
redirect to /api/admin
Here is what my route config looks like:
const routes = {
path: '/',
component: App;
indexRoute: { component: Login },
childRoutes: [
{ path: 'twitter', component: TwitterIn },
]
}
My question is how can I put some login here, something like
if (UserLogged) {
//goto /api/admin
} else {
//behave just like is behaving now
}
2
Answers
If you are using React-Router, wrap your default exported component using
withRouter
. You can import it using:And when you are using the default export, you can do this way:
The
withRouter
higher-order component will pass updatedmatch
,location
, andhistory
props to the wrapped component whenever it renders.And in the constructor or wherever you are checking for the condition, you can use
this.props.history
and redirect this way:If that’s not possible, you can use the
<Redirect />
API, which can be imported this way:This works only if you are inside the render function (I guess).
In my last project, I defined all the routing within a React Component. Within that Component, ‘user’ was defined as a state property set to either ‘null’ (logged out) or a valid user object (logged in). The Component’s rendering logic then returned one set of routes (redirecting to the login page) if the user was logged out and a different set of routes (full application routes) if the user was logged in.