React-router: How to capture navigation and ask for confirmation before navigating away from a route?

Created on 28 Sep 2015  路  8Comments  路  Source: ReactTraining/react-router

I am using react-router v0.13.3 and I tried using willTransitionFrom to capture navigation but it isn't working. I am using ES6 so I cannot use mixins.
My code:

MyComponent.willTransitionFrom = function (transition, component) {
  console.log(transition);
  console.log(component);
  if(!confirm('Are you sure you want to leave?')) {
    transition.abort();
  }
};

Most helpful comment

Just stumbled upon this thread and here's a up-to-date documentation for this: https://reacttraining.com/react-router/web/example/preventing-transitions

All 8 comments

Depends on whether you want this to be global or not.
I did it differently.
I directly listen to BrowserHistory for changes. Look at my code here https://github.com/vojtatranta/avcd-test-app/blob/master/containers/Root.js

I am using v0.13.3. It does not have BrowserHistory.

Ahaaa,
then you can do:

//in case you want to have all this sorted on the level or react and router
Router.run(routes, function (Handler) {
  //this gets callend everytime you visit new page
  //so you can do
  if (Handler == HandlerIWantToConfirm) {
    if (!window.confirm('Realy want to quit?')) {
       React.render(<Handler/>, document.body);
    }
  } else {
    React.render(<Handler/>, document.body);
  }
})

//or onbeforeunload is always a possibility, but I am not sure, how it will work in SPA

thanks @vojtatranta

@knowbody but I am not sure whether this is a legit solution, I am sure that Michael Jackson would do this differently :))

seems legit :+1:

@mjackson will comment if he sees better solution :)

I found a better solution:

class MyComponent extends Component {
  static willTransitionFrom(component, transition) {
    if(!window.confirm('Are you sure you want to leave ?')) {
      transition.abort();
    }
  }
}

Just stumbled upon this thread and here's a up-to-date documentation for this: https://reacttraining.com/react-router/web/example/preventing-transitions

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ArthurRougier picture ArthurRougier  路  3Comments

jzimmek picture jzimmek  路  3Comments

ackvf picture ackvf  路  3Comments

wzup picture wzup  路  3Comments

alexyaseen picture alexyaseen  路  3Comments