Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 13, 2021 09:29 am GMT

Custom React Router Prompt

How to implement the custom prompt on navigation using react-router

Whats the need for custom prompt ?

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 react-router Prompt.

Solution

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.

Step 1

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.

Step 2

Now lets create a custom RouterPrompt component using the useHistory hook from the react-router-dom and ant design component library for the Modal component.

Step 3

Lets create two sample components for navigating between pages. For example, let the first component be Dashboard.jsx and the second component be Home.jsx.

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).

The onOK and onCancel callback props must return boolean value in order to proceed with the route.

Result

Result

Conclusion

You can use any component librarys modal, even your own custom modal or default browser prompt. But just be careful when implementing the history.block.

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.

References

  1. https://reactrouter.com/web/api/Hooks/usehistory
  2. https://reactrouter.com/web/api/history

Original Link: https://dev.to/yadhus/custom-react-router-prompt-40io

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To