'Alternative for Prompt in React Router V6
What is the alternative for Prompt
in React Router V6, has it been deprecated, and also hooks like usePrompt
, useBlocker
are also not available.
<Prompt message="Are you sure you want to leave?" />
Solution 1:[1]
I have a solution to this problem
It's a hook that prompts the user that they are about to lose the changes, and asks if they want to proceed.
The hook needs two files: useNavigatingAway.js
and NavigationBlocker.js
which are based on useLocation
, useNavigation
, and UNSAFE_NavigationContext
; this last one was provided by the people that developed React Router and gives us the alternative to make these kinds of things.
The original article is https://dev.to/bangash1996/detecting-user-leaving-page-with-react-router-dom-v602-33ni, but I changed the names and made it more understandable. I also wrote my version in javascript.
The dialog and menu were developed using MUI, and it's based on React Router Dom 6
Rafael
Solution 2:[2]
Meanwhile, try this package I published https://www.npmjs.com/package/react-router-prompt
You can achieve something similar to <Prompt />
we had in v5
<ReactRouterPrompt when={isDirty}>
{({ isActive, onConfirm, onCancel }) => (
<Modal show={isActive}>
<div>
<p>Do you really want to leave?</p>
<button onClick={onCancel}>Cancel</button>
<button onClick={onConfirm}>Ok</button>
</div>
</Modal>
)}
</ReactRouterPrompt>
Where:
isDirty
=> variable which stores if form is dirty
When isDirty is true: it returns variable isActive
, onConfirm
, onCancel
which can be used by Modal, Dialog or custom prompt component.
isActive
=> when user tries to navigate to different route, this is active and so prompt shall be visible
onConfirm
=> callback to navigate allow user to different route.
onCancel
=> callback to stop user to navigate to different route
Let me know if this helps.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mogsdad |
Solution 2 |