4

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?

1
  • Hava the same issue, did you find a way to avoid this url changing Feb 24, 2017 at 18:02

2 Answers 2

3
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;
       }
    })
  }
}
1

And if your react-route >2.4, you can also use withRouter to wrap your component, this's may be better!

import React, {Component} from 'react';
import {render} from 'react-dom';
import {withRouter} from 'react-router';

export default withRouter(class extends Component {
  state = {
    unsaved: true
  }
  componentDidMount() {
    this.props.router.setRouteLeaveHook(this.props.route, () => {
      if (this.state.unsaved) {
        return false;
          // At here you can give a confirm dialog, return true when confirm true
       }else {
          return true;
       }
    })
  }
  render() {
    return (
      <div>
        <h2>About</h2>
        {this.props.children || "This is outbox default!"}
      </div>
    )
  }
})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.