How to Show a Warning Before Leaving a React Form Page

Have you ever accidentally closed a form page and lost all the entered data? In this guide, we’ll show you how to prevent this by displaying a confirmation message before a user navigates away from the page.

Why Is This Important?

  • Prevents accidental data loss
  • Enhances user experience
  • Works for tab close, page refresh, and back button navigation

Implementing the Solution

1️⃣ Show Warning on Tab Close or Refresh

Use the beforeunload event to prompt users before closing the tab or refreshing the page.

import { useEffect } from "react";

const MyFormComponent = () => {
  useEffect(() => {
    const handleBeforeUnload = (event) => {
      event.preventDefault();
      event.returnValue = "Are you sure you want to leave? Your changes will be lost.";
    };

    window.addEventListener("beforeunload", handleBeforeUnload);

    return () => {
      window.removeEventListener("beforeunload", handleBeforeUnload);
    };
  }, []);

  return (
    <form>
      {/* Your form fields here */}
    </form>
  );
};

export default MyFormComponent;

2️⃣ Prevent Navigation with React Router (Back Button Warning)

If you’re using React Router, intercept the back navigation event.

import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";

const MyFormComponent = () => {
  const [isFormDirty, setIsFormDirty] = useState(false);
  const navigate = useNavigate();

  useEffect(() => {
    const handleBackButton = (event) => {
      if (isFormDirty && !window.confirm("Are you sure you want to leave? Your changes will be lost.")) {
        event.preventDefault();
      }
    };

    window.addEventListener("popstate", handleBackButton);

    return () => {
      window.removeEventListener("popstate", handleBackButton);
    };
  }, [isFormDirty]);

  return (
    <form onChange={() => setIsFormDirty(true)}>
      {/* Your form fields */}
      <button onClick={() => navigate(-1)}>Back</button>
    </form>
  );
};

export default MyFormComponent;

Final Thoughts

With these implementations, your users will no longer lose their form data accidentally. Whether they close the tab, refresh the page, or click the back button, they’ll get a warning before leaving.

Works for:

  • Tab Close & Page Refresh
  • Back Button in React Router