I am building SPA application. I have component with form changes to which could be either saved or canceled depending which button user pressed. I have a flag which indicates that some changes were made in this form.
I am using react-router-dom
v6 for routing like this:
<Routes>
<Route />
<Route />
<Route />
</Routes>
I want to show user a warning when he has unsaved changes and trying to navigate to another page (another route). It seems to me that there is no such a mechanic, I am also still not able to write a pure js script to solve this problem. beforeunload
not working for me because it is only triggered on page refresh.
Is there any way I can achieve this?
2
Answers
This component accompanied by usage of the new createBrowserRouter
react-router-dom
api solved my problem. Anthough it is still not clear how to appropriately use it with query params, blocker seems not be working when I am changing them.Since React-Router v6 doesn’t have the
Prompt
component, you can create your own:Now, we can implement this in code:
Source for custom Prompt component: Alternative for Prompt in React Router V6