I have an antd form, which has 2 submit buttons and I have to perform different tasks on both submit. For this we need to identify which button is clicked, but I am not able to do that.I am trying to get the name of submit button clicked, but on submit it only gives form value and not button name. Below is my code:
import React from "react";
import "./index.css";
import { Button, Form, Input, Select } from "antd";
import type { FormInstance } from "antd/es/form";
const { Option } = Select;
const layout = {
labelCol: { span: 8 },
wrapperCol: { span: 16 }
};
const tailLayout = {
wrapperCol: { offset: 8, span: 16 }
};
const App: React.FC = () => {
const formRef = React.useRef<FormInstance>(null);
const onFinish = (values: any) => {
console.log(values);
};
return (
<Form
{...layout}
ref={formRef}
name="control-ref"
onFinish={onFinish}
style={{ maxWidth: 600 }}
>
<Form.Item name="note" label="Note" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name="gender" label="Gender" rules={[{ required: true }]}>
<Select placeholder="Select a option and change input text above">
<Option value="male">male</Option>
<Option value="female">female</Option>
<Option value="other">other</Option>
</Select>
</Form.Item>
<Form.Item
noStyle
shouldUpdate={(prevValues, currentValues) =>
prevValues.gender !== currentValues.gender
}
>
{({ getFieldValue }) =>
getFieldValue("gender") === "other" ? (
<Form.Item
name="customizeGender"
label="Customize Gender"
rules={[{ required: true }]}
>
<Input />
</Form.Item>
) : null
}
</Form.Item>
<Form.Item {...tailLayout}>
<Button type="primary" name="submit1" htmlType="submit">
Submit1
</Button>
<Button type="primary" name="submit2" htmlType="submit">
Submit2
</Button>
</Form.Item>
</Form>
);
};
export default App;
2
Answers
I have got the solution. I have created onClick function on 2nd button and onClick I have added form.validateFields function for validation.
You can remove htmlType in second button and pass onClick function in second button.