Use NavigationPrompt for custom navigation dialogs
masterThe <NavigationPrompt/> component is a replacement for the standard React Router <Prompt/>. While <Prompt/> is limited to browser-native alert boxes, <NavigationPrompt/> allows you to render custom UI (like modals or dialogs) to confirm navigation.
Important Considerations:
- Browser Security: For security reasons, browsers may still force a vanilla alert box for certain actions, such as reloading the page, closing the tab/window, or navigating away from the site entirely. In these cases, your custom UI might not be shown.
- History Support: Currently, this component is tested with
BrowserHistory. It has known issues withHashHistory. - Multiple Histories: Like the original React Router
<Prompt/>, this component does not work with multipleBrowserHistoryinstances. - Function-based
whenprop: If you pass a function towhen, ensure you check thatnextLocationandactionare defined before using them.
import NavigationPrompt from "react-router-navigation-prompt";
<NavigationPrompt when={this.state.shouldConfirmNavigation}>
{({ onConfirm, onCancel }) => (
<ConfirmNavigationModal
when={true}
onCancel={onCancel}
onConfirm={onConfirm}
/>
)}
</NavigationPrompt>