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?" />
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?" />
You can use this util (checked on react-router-dom v6.9):
import { unstable_useBlocker as useBlocker } from 'react-router-dom'
function Prompt(props) {
const block = props.when
useBlocker(() => {
if (block) {
return ! window.confirm(props.message)
}
return false
})
return (
<div key={block}/>
)
}
export default Prompt
Usage:
<Prompt when={condition} message='Are you sure you want to leave?'/>
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