Detecting user leaving page with react-router

Barry Staes picture Barry Staes · Sep 29, 2015 · Viewed 99.6k times · Source

I want my ReactJS app to notify a user when navigating away from a specific page. Specifically a popup message that reminds him/her to do an action:

"Changes are saved, but not published yet. Do that now?"

Should i trigger this on react-router globally, or is this something that can be done from within the react page / component?

I havent found anything on the latter, and i'd rather avoid the first. Unless its the norm of course, but that makes me wonder how to do such a thing without having to add code to every other possible page the user can go to..

Any insights welcome, thanks!

Answer

jcady picture jcady · Mar 8, 2018

react-router v4 introduces a new way to block navigation using Prompt. Just add this to the component that you would like to block:

import { Prompt } from 'react-router'

const MyComponent = () => (
  <React.Fragment>
    <Prompt
      when={shouldBlockNavigation}
      message='You have unsaved changes, are you sure you want to leave?'
    />
    {/* Component JSX */}
  </React.Fragment>
)

This will block any routing, but not page refresh or closing. To block that, you'll need to add this (updating as needed with the appropriate React lifecycle):

componentDidUpdate = () => {
  if (shouldBlockNavigation) {
    window.onbeforeunload = () => true
  } else {
    window.onbeforeunload = undefined
  }
}

onbeforeunload has various support by browsers.