Home > database >  Show warning message before unmouting React component
Show warning message before unmouting React component

Time:03-07

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.

CodePudding user response:

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

CodePudding user response:

You can use useEffect for this.

something like that :

import React, { useEffect } from 'react';
const ComponentExample => () => {
    useEffect(() => {
        // Anything in here is fired on component mount.
        return () => {
            // Anything in here is fired on component unmount.
            //for ex. alert or console.log('warning')
        }
    }, [])
}
  • Related