Reputation: 2415
how to redirect on componentWillMount using react-router
export class NewStock extends React.Component {
constructor(props, context) {
super(props, context);
}
componentWillMount() {
const { session, dispatch, router } = this.props
if (session.userSessionData.get('logged_in') == false) {
router.transitionTo('/login')
}
};
this code:
router.transitionTo('/login')
only return:
Uncaught TypeError: router.transitionTo is not a function
Upvotes: 2
Views: 10469
Reputation: 66355
Try this.props.history
:
const { history } = this.props
history.pushState(null, '/login') or
history.replaceState(null, '/login')
If your module isn't a direct descendant of the router you can still access this prop by wrapping your component in the withRouter(YourComponent)
HOC (in v4).
Upvotes: 12
Reputation: 7260
What I'm doing is using the onEnter
prop of a route. This allows me to centralize my authentication better. I got my inspiration from the react-router examples
I came here because I was fumbling about with the same aproach as you, but got into an huge mess of unmanageable code VERY SOON.
Hope that for all coming here, you will learn from my mistake.
function requireAuth(nextState, replace) {
if (!UserStore.userIsSignedIn()) {
replace({
pathname: '/login',
state: {nextPathname: nextState.location.pathname}
})
}
}
render((
<Router history={hashHistory}>
<Route path="/" component={PageHeader}>
<IndexRoute component={AssignmentOverview} onEnter={requireAuth}/>
<Route path="login" component={UserLoginForm}/>
<Route path="logout" component={UserLogout}/>
<Route path="profile" component={UserProfile} onEnter={requireAuth}/>
<Route path="assignmentform" component={AssignmentForm} onEnter={requireAuth}/>
</Route>
</Router>
), document.getElementById('content'));
Upvotes: 2