javascriptreactjsreact-routerreact-router-redux

react-router setRouteLeaveHook still updating URL


I'm using react 15.3.1, with react-router 2.4.1 and react-router-redux 4.0.5:

When I trap the routing change with:

this.props.router.setRouteLeaveHook(
    this.props.route,
    this.routerWillLeave
);

private routerWillLeave = () => {
    if (this.state.editing)
        return 'You may have unsaved changes. Are you sure you want to leave?'
};

... I do get my this.routerWillLeave method called, but the URL in the browser still changes, so even if the user stays on the page by deciding not to leave the page, the URL is now wrong. Ideas?


Solution

  • export default class extends Component {
      static contextTypes = {
        router: React.PropTypes.object.isRequired
      }
    
      state = {
        editing: true
      }
    
      componentDidMount() {
    
        this.context.router.setRouteLeaveHook(this.props.route, () => {
           if (this.state.editing) {
              return false;
              // At here you can give a confirm dialog, return true when confirm true
           }else {
               return true;
           }
        })
      }
    }