1

I have a form. I want to show warning before unmounting the form component.

Component is something like this -

import React from "react";

export default function FormComp() {
  const sub = (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    console.log(formData.get("name"));
    //API CALL HERE
  };
  return (
    <div className="test">
      <form onSubmit={sub}>
        <input name="name" />
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

If the component is unmounted when user goes to a different route, how can i show a warning that form changes will not be saved (along with Yes and No option).As soon as FormComp component is unmounted, form data is cleared.

1 Answers1

3

Are you using react-router? This can be easy with that.

If yes, then you can do something like this:

import { Prompt } from 'react-router'

const FormCompComponent = () => (
  <>
    <Prompt
      when={formIsHalfFilledOut}
      message='You have unsaved changes, are you sure you want to leave?'
    />
    {/* Component JSX here */}
  </>
)

For more details check this out: https://v5.reactrouter.com/core/api/Prompt

Harry
  • 754
  • 2
  • 16
  • usePromt and useBlocker are not present in react-router-dom v6 :( https://github.com/remix-run/react-router/issues/8139 – Peeyush Gupta Mar 07 '22 at 14:37
  • Oops! Thats right. Didn't know you were on v6. You have two options: Either create your own component or downgrade to v5. I suggest downgrade to v5. – Harry Mar 07 '22 at 14:59