0

Currently, I want to show a message to the user before the user navigates away from the page with unsaved changes. I looked into using react-router Prompt component and I have it setup like this:

import { Prompt } from 'react-router-dom';

function MyForm() {
  const [isFormIncomplete, setIsFormIncomplete] = useState(true);
  return (
    <div>
     <form>{/*form code*/}</form>
     <Prompt
       when={isFormIncomplete}
       message="Are you sure you want to leave?" />
    </div>
  )
}

Currently, it showing the confirmation dialog just fine but I'm confused on how to override the cancel button. Right now, on cancel, it still navigates away from the page (same with ok) but on cancel, I just want to dismiss the browser confirmation dialog and not navigate away from the page. How do I do that? I don't see anything in the docs for overriding cancel behavior of the browser dialog?

Euridice01
  • 2,510
  • 11
  • 44
  • 76
  • How do you handle the navigation? You should use Link or useHistory from `react-router-dom` – aytek Jun 15 '21 at 15:35
  • I use location.hash and navigate based on url params and page information. It's not ideal but that's what we have now. Eventually, we do want to migrate to react-router fully but right now, our task to show confirmation dialog before user navigates away and we want to handle both options (on cancel and on ok). Solutions online suggest react-router which is mostly working except the issue above – Euridice01 Jun 15 '21 at 15:42
  • 1
    You can't use Prompt if you are not using react-router for navigation. [This](https://stackoverflow.com/questions/821011/prevent-a-webpage-from-navigating-away-using-javascript) may help you. – aytek Jun 15 '21 at 16:11
  • I have a question though, why does Prompt actually work for navigating back properly but not on cancel if I'm not using it for navigation? – Euridice01 Jun 15 '21 at 16:42
  • beforeunload unfortunately doesn't allow custom message and I need to use custom message, now what? – Euridice01 Jun 15 '21 at 16:42
  • I don't believe there is anything to override. Have you looked at the [preventing transitions example](https://reactrouter.com/web/example/preventing-transitions) to get an idea for usage? Are you attempting to navigate using a means other than solutions provided by react-router-dom? – Drew Reese Jun 15 '21 at 18:27
  • Yes. We are doing navigation without using react-router and I thought Prompt would be a quick fix for our confirmation dialog issue. Navigation is a bit complex but on a simplistic level, we are navigating based on url params and path and setting the location hash based on the new path to navigate to and dispatching actions to check if we should navigate or remain on the page based on navigation state object in redux. – Euridice01 Jun 15 '21 at 18:41

0 Answers0