How to implement the custom prompt on navigation using react-router
Most of the react projects follow the UI design system for their components. In order to achieve the same design consistency across the app, they reuse the components. However to block the navigation in case there are some unsaved user data, default browser prompt is the most common and easy way to block the user from navigating to different routes. But the popup does not match your library component.
There is no official docs explicitly mentioning how to use the custom modal instead of the default
There are few simple steps to be followed in order to get the required result. Each step contains 100% working code snippets. You can use it in your projects.
We need to disable or block the default browser prompt. This can be done by passing an empty callback to the
getUserConfirmation function prop of the BrowserRouter.
Now let’s create a custom RouterPrompt component using the
useHistory hook from the react-router-dom and ant design component library for the Modal component.
Let’s create two sample components for navigating between pages. For example, let the first component be
Dashboard.jsx and the second component be
The home component contains our custom RouterPrompt component. The prompt is triggered on the page change and also based on the
when prop. The when prop is used to conditionally trigger the prompt. For instance, if the when prop is set to true , the prompt will be shown every time page navigates (from home route to other routes or navigate forward / back).
onCancel callback props must return boolean value in order to proceed with the route.
You can use any component library’s modal, even your own custom modal or default browser prompt. But just be careful when implementing the
By following the above steps you can achieve the desired solution. The code is 100% working. You can copy the code snippets to your applications to save time.