Prevent component from unmounting - showing notification to users before opening other component

In my web app there is a form where users put in data. If they want to navigate to other component or back, I want to notify them that changes were made to form and show them confirmation dialog. I know how to implement this if users click on back button on top of the form, but don't have any idea how to handle it when users click on sidebar menu options. (there is a sidebar with multiple links to other components - using react-router).

I have tried something using componentWillunmount() but no luck since component gets unmounted in any case.

If anyone has experience in this I would really need some help.


Try the routerWillLeave hook, here is a example from react-router's documentation:

const Home = withRouter(

    componentDidMount() {
      this.props.router.setRouteLeaveHook(this.props.route, this.routerWillLeave)

    routerWillLeave(nextLocation) {
      // return false to prevent a transition w/o prompting the user,
      // or return a string to allow the user to decide:
      if (!this.state.isSaved)
        return 'Your work is not saved! Are you sure you want to leave?'

    // ...



 ? How to access the correct `this` context inside a callback?
 ? How does use strict impact this keyword in the context of call and apply method of a Function object in Javascript ES5 and ES6
 ? What does the value of 'this' mean in es6 classes
 ? Can I yield from an inner function?
 ? React Native - unexpected identifier
 ? How can I emulate a synchronous call with generators in javascript?
 ? Javascript Set: any way to override comparison between elements?
 ? angular2 forms - cannot read property replace of undefined
 ? How can I convert this async callback to a generator?
 ? Put router configuration in a separate file in Aurelia