1

I am working on a dynamic form where the form gets submitted automatically when all the required fields are filled. We don't have any submit button in the form. Now suppose a user has filled a few of the form fields and tries to leave the form by clicking any navigation link in the application, we need to warn the user with a pop up showing the message "You have unsaved changes. Navigating away from this view will revert these changes. This action cannot be undone. Are you sure you want to continue?". Now if the user clicks on the continue it will redirect to the navigated page and if he clicks on cancle it will stay on the same page(form).

Here we are using ReactJS but not using any react routing in the application. We have tried all possible ways but were not able to come up with any solution. Has somebody faced this scenario before or has any idea how to approach the problem?

overflow
  • 11
  • 5
  • 1
    What did you tried ? What worked, what didn't ? – Marius ROBERT May 24 '22 at 08:24
  • What about using onbeforeunload event? As long as you don't use react-router, then you must navigate from the form or hide it manually using a flag let's say. Either cases, you will have the control. Check this answer https://stackoverflow.com/a/821227/6252111 for more information about the event. – Abdulrahman Hashem May 24 '22 at 08:25
  • I have tried to keep one variable(useRef) when there is any changes in the form which is not saved yet. I have tried to check if there is any unsaved changes using that variable on unmounting using useEffect. But can not revert the unmounting of a component even if the user click on the cancel button. – overflow May 24 '22 at 08:30
  • Please provide enough code so others can better understand or reproduce the problem. – Ethan Jun 04 '22 at 01:38

1 Answers1

0

You could use native browser API beforeUnload.

  ...
  const beforeunload = (e) => {
    // You can add logic for confirmation here.
    if (dataUnsaved) {
      e.preventDefault();
      e.returnValue = true;
    }
  }

  useEffect(() => {
    window.addEventListener('beforeunload', beforeunload);
    
    return () => {
        window.removeEventListener('beforeunload', beforeunload);
    }

  }, [])

  return (
   ...
  )
...
Satel
  • 169
  • 1
  • 9
  • Thanks for your answer @Satel. I have tried and created one [Codesandbox](https://codesandbox.io/s/nervous-feynman-9bieqv) but its not working using the event. Am I missing something here? – overflow May 24 '22 at 09:21
  • Excuse me but I can't access to your CodeSandBox, not sure why. BTW, would you please check this, https://developer.mozilla.org/en-US/docs/Web/API/BeforeUnloadEvent? – Satel May 25 '22 at 13:28
  • This not working if redirect to react route page – Alan Yong Jun 09 '22 at 09:03