16

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?" />
Praveen Rao Chavan.G
  • 2,772
  • 3
  • 22
  • 33
  • 6
    React-router-dom v6 no longer exports a Prompt component (or any sort of navigation blocking). I think they may introduce it later, but in the meantime you'll need to revert back to v5 if you want/need to continue using the Prompt component. See this [discussion](https://github.com/remix-run/react-router/issues/8139) on github. – Drew Reese Dec 01 '21 at 04:07

2 Answers2

7

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?'/>
o.z
  • 1,086
  • 14
  • 22
-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.

Edit navigating-prompt

The dialog and menu were developed using MUI, and it's based on React Router Dom 6

Rafael

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Rafael
  • 2,413
  • 4
  • 32
  • 54
  • 2
    I expect you have downvote(s) because your answer comes close to being a [link-only answer](https://meta.stackexchange.com/questions/225370/your-answer-is-in-another-castle-when-is-an-answer-not-an-answer). A link - even a fancy one - to another place to find code lowers the value of this answer because (a) I have to look somewhere else, (b) that link might die, and (c) without the code IN this answer, my ability to find it via searching here diminishes. It would be better to embed your javascript as a snippet. – Mogsdad Mar 11 '22 at 14:59
  • 2
    Doesn't work on react-router-dom 6.5: navigator.block is not a function – Emaborsa Dec 29 '22 at 13:46