reactjsantdonbeforeunloadunload

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


Solution

  • 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)