Rich
Rich

Reputation: 185

How to add Window: beforeunload event to antd form

Hi How can we add Window: beforeunload event to an antd form? For a single field, we can implement as below https://codesandbox.io/s/cool-brattain-uufyg?file=/src/App.js:452-558

Upvotes: 0

Views: 992

Answers (2)

Fiodorov Andrei
Fiodorov Andrei

Reputation: 2028

You can use method onFieldsChange to understand when block the navigation:

import React, { useEffect } from "react";
import { Form, Input, Button } from "antd";

const { Item } = Form;

const App = () => {
  const [cannotLeave, setCannotLeave] = React.useState(false);

  useEffect(() => {
    const handler = (e) => {
      e.preventDefault();
      if (!cannotLeave) {
        return;
      }
      e.returnValue = true;
    };

    window.addEventListener("beforeunload", handler);
    return () => window.removeEventListener("beforeunload", handler);
  }, [cannotLeave]);

  const handleFieldsChange = () => setCannotLeave(true);

  return (
    <Form onFieldsChange={handleFieldsChange}>
      <Item name="test">
        <Input placeholder="Test " />
      </Item>
      <Item name="test">
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Item>
    </Form>
  );
};

export default App;


Live example:

Edit colSpan and rowSpan - antd@4.18.5 (forked)

Upvotes: 1

Adem &#199;ırak
Adem &#199;ırak

Reputation: 241

Antd form instance has a getFieldsValue method (https://ant.design/components/form/#FormInstance).

You can get all values by calling form.getFieldsValue(true) and check if any field is filled.

Upvotes: 0

Related Questions