Reputation: 11585
I'm looking how to control which routes are available, based on a users privilege level which is in the context.
I found a nice example, but it relies on localStorage for storing user auth state. I would prefer to keep everything "in state".
I've been playing around for a while, but I can't seem to pass context into the onEnter()
prop of a <Route ... />
. My closest solutions are looking terribly hacky and I'm starting to think making react-router aware of context is a bad strategy.
Has anyone got an example? or can confirm the router is should not be making decisions based on context?
Thanks
Edit: I have been pointed to the react-router examples, it looks promising: https://github.com/reactjs/react-router/tree/master/examples
Upvotes: 2
Views: 231
Reputation: 20037
Although localStorage
is pretty reliable, it might not be supported or user could delete it.
I would suggest you to use redux & react-redux instead, then you can easily access the state
of your application, code would look something like this:
const Root = ({ store }) => (
function authenticateUser(nextState, replaceState, callback) {
const state = store.getState()
// do your thing - forbid, grant access etc...
}
<Provider store={store}>
<Router>
<Route path="/" component={App} onEnter={authenticateUser} />
</Router>
</Provider>
);
Moreover redux
helps you scale react
applications. It might be a little difficult and overwhelming to understand redux
at first, but it's ok - because the effort is well worth it and will pay off.
Usage of redux with react-router.
Upvotes: 1