Skip to content Skip to sidebar Skip to footer

How Can I Prevent The Unmount In React Components?

I'm trying to implement a feature in my app where when the user tries to navigate away from an un-submitted form, they're given an confirm that asks them if they're sure they want

Solution 1:

This is best handled via react-router: setRouteLeaveHook.

componentWillMount() {
    this.unregisterLeaveHook = props.router.setRouteLeaveHook(props.route, this.routerWillLeave.bind(this));
}

routerWillLeave(nextLocation) {
  returnfalse;        
}

And when component is unmounted, unregister the leave hook:

componentWillUnmount() {
    this.unregisterLeaveHook();
}

Solution 2:

Using react-router you can easily prevent route change(which will prevent component unmount) by using Prompt.

import { Prompt } from'react-router';

constBlockingComponent = ({ isBlocking }) => (
  <div><Promptwhen={isBlocking}message={location =>
        `Are you sure you want to go to ${location.pathname}`
      }
    />
    {/* Rest of the JSX of your component */}
  </div>
);

Here isBlocking should be a bool indicating whether a blocking prompt should be shown or not. You can find a complete demo on react-router website

This method will work for BrowserRouter and HashRouter, but if you are using MemoryRouter, you need to create your Router as shown below then use Prompt in your components:

<MemoryRouter
  getUserConfirmation={(message, callback) => {
    callback(window.confirm(message));
  }}
>
  {/* Your App */}
</MemoryRouter>

You need to manually pass the getUserConfirmation prop which is a function. You can modify this function as you like in any Router(Browser, Memory or Hash) to create your custom confirmation dialog(eg. a modal) instead of using the browser's default confirm.

Solution 3:

I wouldn't recommend doing that in componentWillUnmount. I usually want to do that in the store (if you are using flux architecture). It is usually the store that needs to keep track of all the data. The componentWillUnmount function is were you would want to unmount the store listener.

Post a Comment for "How Can I Prevent The Unmount In React Components?"