I am creating a page in which the user needs to enter the details to add the product to the product list. If the user accidentally moves out of that page after inputting some data in the form, confirmation should be mandatory from the user before moving out. But I am struggling with this requirement. I am using the react-hook-form
for storing the data in the JSON server.
I am using a state leave
, if it true then alert the user before moving out else nothing.
const [leave, setLeave] = useState(false);
Now, I don't know where and how to use this state for displaying the alert box before leaving. Here my form which will render.
render (
<Form onSubmit={handleSubmit(onSubmit)}>
<Form.Row>
<Form.Group as={Col} className="mr-5">
<Form.Label column>Product Name</Form.Label>
<Form.Control
name="productName"
placeholder="Enter product Name"
required
ref={register}
/>
</Form.Group>
</Form.Row>
<Button variant="success" type="submit" className="text-white mt-5">
Add New Product
</Button>
</Form>
<Prompt when={Leave} message="Are you sure you want to leave ?" /> {/*Here I have promted*/}
);
For simplicity, I have given only one input field. Now function definition of onSubmit is given below.
const onSubmit = (formData) => {
setLeave(true); //here I am setting this true
axios.post("http://localhost:4000/products", formData);
navigation.push({
pathname: "/productList",
state: { added: "pass" },
});
};
This will work when I submitting the form but I want to prompt when the user clicks on the back button or any navigation link.