When we are dealing with form input, we need to cancel navigation to a different page to ensure that the form is saved. This is a bit tricky than it sounds. How should the app behave if the user

  1. Closes the browser.
  2. Moves to a different website.
  3. Moves to another page within the same website.

There is not much that a React app can do to handle the cases 1. and 2. The onbeforeunload function should be used to check if the user is navigating away from a site.

The onbeforeunload function shows a confirm dialog. If the user wants to stay on the site, the navigation is cancelled.

There are more options available if the user is navigating to a different page on the same app. A custom dialog (another React component) can be presented to the user which asks the user to save the form and continue navigation or cancel the navigation.

React router has hooks which run when certain events happen. One such event is “Route Leave”. The setRouteLeaveHook can used to set a function which will get triggered when the user leaves the current route or page.

In the routerWillLeave function, returning false will cancel navigation. If the user has not saved the work, we return false to cancel the navigation as shown below.

Finally, if the user pressed OK to leave the page, then we unregister the hook we set earlier. The unregister function is returned when we set the hook earlier.

The above code snippets are the bare minimum that should be present in your custom solution. There can be more variations to the above code Рlike opening up custom dialog, proceeding with various actions in response to button clicks, etc.

Cancel navigation to a different page in a React app
Tagged on:
  • Kesavaraja Krishnan

    can you please add live demo . that will be appreciated.