React-router: preventing navigation on the target route

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?

+7
javascript reactjs react-router browser-history
source share
1 answer

The reaction cannot prevent navigation after calling history.push.

You have to encapsulate the history service with a custom one that will check if it is possible to navigate, and if so, call history.push. otherwise, prevent navigation and save state.

+1
source share

All Articles