Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Antd form remote submit

Tags:

reactjs

antd

I want to trigger the submit button outside the antd form

Here is my code

<Form
          {...layout}
          name="basic"
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >

     <Form.Item
        label="Username"
        name="username"
        rules={[
          {
            required: true,
            message: 'Please input your username!',
          },
        ]}
      >
        <Input />
      </Form.Item>
    
    <Form.Item {...tailLayout}>
           // Submit button here works well
          </Form.Item>
</Form>

I want this outside form tag, please suggest

 <Button type="primary" htmlType="submit">
     Submit
 </Button>
like image 680
ramamoorthy_villi Avatar asked Aug 26 '26 17:08

ramamoorthy_villi


2 Answers

You can try this way:

 const [form] = Form.useForm();

  const handleFinish = (values) => {
    console.log("values: ", values);
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <MyForm form={form} onFinish={handleFinish} />
      <Button onClick={() => form.submit()}>Submit</Button>
    </div>
  );
export const MyForm = ({ form, onFinish }) => {
  return (
    <Form
      form={form}
      onFinish={onFinish}
      initialValues={{ username: "John Doe" }}
    >
      <Form.Item name="username">
        <Input />
      </Form.Item>
    </Form>
  );
};

Edit strange-currying-ttkv1

like image 75
J. Doe Avatar answered Aug 29 '26 08:08

J. Doe


If the form and the button are not in the same component then it is hard to create same reference for the form in 2 different place. But I found an other easy way:

<Form id="myForm">...</>
...
<Button form="myForm" key="submit" htmlType="submit">
  Submit
</Button>

This is the answer from this issue

like image 21
Andy Nguyen Avatar answered Aug 29 '26 09:08

Andy Nguyen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!