Toby
Toby

Reputation: 13385

React-Router v4 - Prevent Transition With Function

I was able to prevent navigation as per the v4 docs, but I'm trying to hook up a function so that I can use a modal instead of an alert.

Function:

abandonForm = (route) => {
  this.props.showModal('confirm');
  console.log('leaving..');
}

In my page:

<NavigationPrompt when={true} message={(location) => this.abandonForm('confirm')} />

this.props.showModal('confirm') activates the modal successfully, but behind the modal the page still transitions - how can I prevent transition until a button in the modal is clicked?

Upvotes: 2

Views: 2376

Answers (2)

Rajat Sharma
Rajat Sharma

Reputation: 86

Use:

this.unBlock = this.props.history.block((location, navigateToSelectedRoute) => {
  // save navigateToSelectedRoute eg this.navigateToSelectedRoute = 
  // navigateToSelectedRoute;
  // use this.navigateToSelectedRoute() afterwards to navigate to link
  // show custom modal using setState
});

and when unblocking is done then call this.unBlock() to remove the listener.

Documentation here for history api

Upvotes: 0

Stefan Dragnev
Stefan Dragnev

Reputation: 14473

Browsers only allow navigation cancellation by means of the alert box that you've mentioned. This restriction is motivated by phishing/scamming sites that try to use javascript gimmicks to create user experiences that convincingly mimic something that a browser or the OS would do (whom the user trusts). Even the format of the text shown in the alert box is crafted so that it's obvious that it originates from the site.

Of course, as long as the current URL stays within your app, you have control over it using react-router's history. For example you can do the following on navigation:

  • allow the navigation without confirmation
  • immediately navigate back to the previous location, but now with a modal on top
  • navigate away for real this time when the user clicks on a button in the modal.

The disadvantage of this approach (leaving out the sheer complexity of it) is that the user will not get a confirmation dialog if they try to navigate to a different site entirely.

Upvotes: 2

Related Questions