0

I'm trying to create a form using modal, not able to use Form.useForm() since it is a class it throws invalid hook call error.

What can I use as an alternative for Form.useForm(), I also tried using Form.create() but it is deprecated.

import React from "react";
import { inject, observer } from "mobx-react";
import { LoginOutlined  } from "@ant-design/icons";
import { Input, Button, Modal, Tooltip, message, Form } from "antd";
import * as mobx from "mobx";
import "./index.less";

@inject("store")
@observer
class AddNewEntry extends React.Component {
  constructor(props) {
    super(props);
  }

  state = {
    showModal: false,
    firstName: "",
    middleName: "",
    lastName: ""
  };

  render() {
    const { showModal, firstName, middleName, lastName } = this.state; 
    const [form] = Form.useForm(); 

    const handleNewEntry = () => {
      this.setState({ showModal: true })
    }

    const handlefirstName = (e) => {
      this.setState({ firstName: e.target.value });
    };

    const handlemiddleName = (e) => {
      this.setState({ middleName: e.target.value });
    };

    const handlelastName = (e) => {
      this.setState({ lastName: e.target.value });
    };

    const handleCancel = () => {
      this.setState({ showModal: false })
    };

    const handleOk = () => {
      var firstNameId = "";
      var middleNameId = "";
      var lastNameId = "";
      if (firstName != "" && middleName != "" && lastName != "") {
        if (firstName != "") {
          const prefix = "n";
          const incrementNum = "01" + 1;
          firstNameId = prefix + incrementNum;
        }
        if (middleName != "") {  
          middleNameId = firstNameId + "01";
        }
        if (lastName != "") {
          lastNameId = middleNameId + "02";
        }
        this.props.store.addNewEntry(firstNameId, firstName, { middleNameId: middleNameId, middleName: middleName, lastNameId: lastNameId, lastName: lastName });
        this.setState({ showModal: false });
      } else {
        message.warning("Please Enter All Names!")
        this.setState({ showModal: true });
      }
    };

    return (
      <>
        <Tooltip placement="top" title="Add New Entry">
          <Button
            icon={<LoginOutlined />}
            size={"small"}
            disabled={this.props.disable}
            onClick={handleNewEntry}> New Entry </Button>
        </Tooltip>
        <Modal
          title="Enter Name you want"
          visible={showModal}
          // onOk={handleOk}
          // onCancel={handleCancel}
          zIndex={10}
          className="modalWidth"
          footer={[
            <><Button onClick={handleCancel}>
              Cancel
            </Button>
              <Button htmlType="submit" form={form} type="primary" onClick={handleOk}>
                Ok
              </Button></>
          ]}
        >
          <Form
            form={form}
            labelCol={{ span: 6 }}
          >
            <Form.Item
              style={{ marginBottom: "4px" }}
              label="First Name"
              name="First Name"
              rules={[{ required: true, message: 'First name is required!' },
              {
                pattern: new RegExp(/^[a-zA-Z0-9_.-]*$/),
                message: "field does not accept special characters"
              }]}
            >
              <Input
                placeholder="Enter First Name"
                value={firstName}
                onChange={handlefirstName}
                className="inputWidth"
              />
            </Form.Item>
            <Form.Item
              style={{ marginBottom: "4px" }}
              label="Middle Name"
              name="Middle Name"
              rules={[{ required: true, message: 'Middle name is required!' },
              {
                pattern: new RegExp(/^[a-zA-Z0-9_.-]*$/),
                message: "field does not accept special characters"
              }]}
            >
              <Input
                placeholder="Enter Middle Name"
                value={middleName}
                onChange={handlemiddleName}
                className="inputWidth"
              />
            </Form.Item>
            <Form.Item
              style={{ marginBottom: "4px" }}
              label="Last Name"
              name="Last Name"
              rules={[{ required: true, message: 'Last name is required!' },
              {
                pattern: new RegExp(/^[a-zA-Z0-9_.-]*$/),
                message: "field does not accept special characters"
              }]}
            >
              <Input
                placeholder="Enter Last Name"
                value={lastName}
                onChange={handlelastName}
                className="inputWidth"
              />
            </Form.Item>
          </Form>
        </Modal>
      </>
    );
  }
}

export default AddNewEntry;

Can someone please help me to overcome this issue? How can I create a Form in class component

Got below error :

bundle.js:83800 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
    at Object.throwInvalidHookError (bundle.js:83800:9)
    at Object.useRef (bundle.js:101179:21)
    at useForm (bundle.js:45598:52)
    at Object.useForm (bundle.js:8392:74)
    at AddNewEntry.render (bundle.js:17285:65)
    at allowStateChanges (bundle.js:35506:12)
    at bundle.js:33637:77
    at trackDerivedFunction (bundle.js:36121:18)
    at Reaction.track (bundle.js:36707:18)
    at AddNewEntry.reactiveRender [as render] (bundle.js:33633:14)

Also,I need to remove form fields on clicking OK button.

pruthvi
  • 43
  • 5
  • How are you rendering `AddNewEntry` inside `Login`? That warning means that when you render the same component multiple times each one of the must have a unique `key` attribute. [This](https://reactjs.org/docs/lists-and-keys.html) will explain your warning – leo Jan 19 '23 at 09:36
  • Hi @leo thanks for responding, I have updated the error. Sorry I did not notice, forgot to add the latest error. could you please check now? – pruthvi Jan 19 '23 at 09:55
  • Hooks cannot be used in class components. You can use a ref and pass it to Form. `formRef = createRef()`. Also you are not using that form except passing to Submit Button which is not required and button form prop and antd form have different type. I recommand to move all functions outside the render. – Muhammad Nouman Rafique Jan 19 '23 at 15:31
  • it worked with createRef() thanks :) @MuhammadNoumanRafique – pruthvi Jan 23 '23 at 08:14

1 Answers1

0

Referred below example it worked in my case, Just sharing if it helps someone :)

Antd clear form after submit in reactjs

pruthvi
  • 43
  • 5