4

I'm doing a multistep form and I want to prevent the user from leaving during the process. The idea is that if the users try to go away while doing the process, show them a confirmation message, if they confirm, then redirect them to the home page, else stay in the current page.

Currently I am using a < Prompt/> from React router

<Prompt when={isLeaving} message={"Changes will be lost"}/>

This displays a confirmation, so I would like to redirect the users to the home page if they accept.

I tried also with event listeners and I almost get it done. The only problem with this was that it only detects popstates.

useEffect(() => {    
    if(!popEventListnerAdded){
      window.addEventListener('popstate', handleBackButton, false);
      popEventListnerAdded = true;
    }    
  }, []);
const handleBackButton = event => {
      var r = window.confirm("You will need to begin the process again are you sure?");
      if (r === true) {
          // Call Back button programmatically as per user confirmation.
          history.push("/Home"); 
      } else {
          // Stay on the current page.          
          history.push(location.pathname)                  
      }              

  }

Is there any way to add a function when the user clicks OK on the < Prompt /> so I can redirect them?

Thanks a lot!

lorenzoajt
  • 105
  • 2
  • 7
  • Possible duplicate: https://stackoverflow.com/questions/32841757/detecting-user-leaving-page-with-react-router – Tobi Mar 08 '23 at 10:29

0 Answers0