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({ when, message }) {
useBlocker(() => {
if (when) {
return ! window.confirm(message)
}
return false
}, [when])
return <div key={when} />
}
export default Prompt
Usage:
<Prompt when={condition} message='Are you sure you want to leave?'/>
** Edit, Feb 2024: **
Use react-router-prompt, availabe with react-router-dom >= 6.19
Since React Router v6.7.0, the unstable_usePrompt hook is available. It requires using a data router, e.g. by calling createBrowserRouter (which is recommended for all new React Router web projects).
The documentation provides the following example:
function ImportantForm() {
let [value, setValue] = React.useState("");
// Block navigating elsewhere when data has been entered into the input
unstable_usePrompt({
message: "Are you sure?",
when: ({ currentLocation, nextLocation }) =>
value !== "" &&
currentLocation.pathname !== nextLocation.pathname,
});
return (
<Form method="post">
<label>
Enter some important data:
<input
name="data"
value={value}
onChange={(e) => setValue(e.target.value)}
/>
</label>
<button type="submit">Save</button>
</Form>
);
}
However, useBlocker is recommended instead for providing consistency across browsers as it enables handling how the confirmation message is styled. (It also requires a data router.) As of React Router v6.19.0, it no longer has the unstable prefix whereas there are no plans to remove the unstable prefix from unstable_usePrompt due to its non-deterministic behavior in different browsers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With