Next.js Discord

Discord Forum

How to prevent user from leaving the page if they haven't completed the form?

Unanswered
Manx posted this in #help-forum
Open in Discord
ManxOP
Is there a way to prevent the users from leaving the page on which we have a form, in case the form is "dirty" (as in, user started typing in some fields, uploaded something, but hasn't submitted the form)?

I know of "beforeunload" event, but that only takes into consideration closing the tab, reloading the page, or redirecting to another page using a regular link.

However I wanted to know if theres a simple way to achieve the same thing, if the user clicks on a "Go Back" button from the browser or link using <Link/> component?

1 Reply

You could use the context api or some state management library to store the form status and enable/disable links on the page accordingly. But thatsarguably not a good practice. Instead consider saving the form data to localStorage so that you can skip form steps that have already been completed.