I have stored in redux if a user is authenticated or not. What I want to do is, once I go to localhost:3000/ I want it to display homepage if user is not authenticated or display the dashboard if the user is authenticated. This is what I have so far.
export default (
<Route path="/" component={App} >
<IndexRoute component={HomePage} />
<Route path="/dashboard" component={Dashboard} />
<Route path="*" component={NotFound} />
</Route>
);
I would like the IndexRoute to be conditional on authentication.
In the HomePage component you can render two other components based on authentication. For example
class HomePage extends Component {
//...
render() {
if (currentUser) return <Dashboard /> // if user exists in the store
else if (fetchingCurrentUser) return <LoadingView /> // if you need to fetch the user show a loading page
else return <UnauthenticatedHomeView /> // else, return a homepage for unauthenticated users
}
}
This way you can eliminate the '/dashboard' route altogether so the user doesn't have to travel to that route to get to their dashboard. Also, HomePage just acts as a container for the different possible components it can render inside of it.
Your routes would then look like this.
export default (
<Route path="/" component={App} >
<IndexRoute component={HomePage} />
<Route path="*" component={NotFound} />
</Route>
);
Another note: you can also hook up the onEnter function to a route to run when the route is about to entered. Here you can do some other authenticated to protect a route. However, the example implementation above would have to change if you use onEnter but you now know you have that option.
You could use conditional rendering in JSX.
export default (
<Route path="/" component={App} >
{isLoggedIn ? (
<IndexRoute component={HomePage} />
) : (
<IndexRoute component={Dashboard} />
)}
</Route>
);