How can I prevent the unmount in React Components?
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.
Using react-router you can easily prevent route change(which will prevent component unmount) by using Prompt
.
import { Prompt } from 'react-router';
const BlockingComponent = ({ isBlocking }) => (
<div>
<Prompt
when={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
.
This is best handled via react-router: setRouteLeaveHook.
componentWillMount() {
this.unregisterLeaveHook = props.router.setRouteLeaveHook(props.route, this.routerWillLeave.bind(this));
}
routerWillLeave(nextLocation) {
return false;
}
And when component is unmounted, unregister the leave hook:
componentWillUnmount() {
this.unregisterLeaveHook();
}