I have a function checkAuth which I want to trigger before entering '/home'. I am using react-router 2.6.0
My code (relevant part) looks like this -
import React from 'react';
import {Route, IndexRoute, browserHistory, IndexRedirect} from 'react-router';
import Layout from './Layout.jsx';
import HomePage from './HomePage.jsx';
import AuthPage from './AuthPage.jsx';
function checkAuth(){
if(localStorage.getItem('auth')!='true'){
console.log('inside'); // this is getting called
browserHistory.push("/auth");
}
}
const routes=(
<Route path="/" component={Layout}>
<IndexRedirect to="/home" />
<Route path="/home" component={HomePage} onEnter={checkAuth} />
<Route path="/auth" component={AuthPage} />
</Route>
);
export default routes;
Now the problem is that it is printing 'inside' in console and url changes from '/home' to '/auth' but inside Layout, I get Home component instead of Auth (desired in the current situation) component.
My Layout component -
import React from 'react';
class Layout extends React.Component{
constructor(props){
super(props);
};
render(){
return(
<div>
<div id="container">{this.props.children}</div>
</div>
);
}
}
export default Layout;
I also tried browserHistory.replace('/auth')
but that also did not help me.
I followed this link which suggested that layout component might not be able to render Auth component after Home component has rendered.
But I need some more insights on this problem. Also any approach to the solution.
Thanks.