Skip to content

Instantly share code, notes, and snippets.

@benbarber
Created February 9, 2017 14:20
Show Gist options
  • Save benbarber/7ae5719fccf9f2c1c33d21d592d50bcf to your computer and use it in GitHub Desktop.
Save benbarber/7ae5719fccf9f2c1c33d21d592d50bcf to your computer and use it in GitHub Desktop.
Confirm before navigation with React Router
import React from 'react'
class MyComponent extends React.Component {
componentDidMount() {
this.props.router.setRouteLeaveHook(this.props.route, this.routerWillLeave)
}
routerWillLeave(nextLocation) {
// return false to prevent a transition w/o prompting the user
if(!window.confirm('Are you sure you want to leave?')) {
return false
}
// or return a string to allow the user to decide
return nextLocation
}
// ...
}
export { MyComponent }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment