I am using response-router with a history of useQueries(createHashHistory)() , and I have several routes that I want to prevent navigation depending on the route configuration.
Thus, config config looks like this:
<Route path="/" name={RouteNames.APP} component={AppContainer}> <Route path="view-1" onEnter={ view1onEnter } onLeave={ view1onLeave } component={ View1 } canNavigate={ false } /> <Route path="view-2" onEnter={ view2onEnter } onLeave={ view2onLeave } component={ View2 } canNavigate={ true } /> ... </Route>
So let's say I'm on #/view-2 and call an action like history.push({pathname: '/view-1'}); . But as soon as the view-1 route has the flag canNavigate={false} - I want to prevent navigation to it and show the message without changing the hash and any other side effects (for example, calling onLeave hook view-2 ).
I was thinking about listening to history :
history.listenBefore((location, callback) => { //eg callback(false) to prevent navigation })
but I cannot get an instance of the route to check the canNavigate flag.
Later, I found out that history has a match method that actually gets the following router state based on a given location :
history.listenBefore((location, callback) => { history.match(location, (error, redirectLocation, nextState) => { const route = _.last(nextState.routes); if (route.canNavigate) { callback(); } else { callback(false); } }); })
but the problem is that history.match calls onLeave hook for view-2 inside (which can, for example, clear the state even if the user remains in view-2 ).
Question : is it possible to prevent navigation from view-2 without any changes in the history / router and make this decision based on the configuration of the target route?
javascript reactjs react-router browser-history
Kiril
source share