How to submit form component in modal dialogue using antd react component library
There is a new solution that looks much cleaner:
<Form id="myForm">
...
<Modal ... footer={[ <Button form="myForm" key="submit" htmlType="submit"> Submit </Button> ]}> <CustomForm /></Modal>
This works because of the Button's form attribute. Browser support
Original solution's author: https://github.com/ant-design/ant-design/issues/9380
You can study official example: https://ant.design/components/form/#components-form-demo-form-in-modal
My solution was to wrap modal dialogue and form components in a new wrapper parent component in which I validate the child form component in handleCreate method. I have used the ref attribute to reference the myForm child component inside the FormOnModalWrapper component. I am passing the parent handlers via props from the wrapper parent component to myForm component instance.
class FormOnModalWrapper extends React.Component {... constructor(props) { this.state = { visible: false .... }... showModal = () => { this.setState({ visible: true, }); } handleCreate = () => { const form = this.form; form.validateFields((err, values) => { if (err) { return; } console.log('Received values of form: ', values); form.resetFields(); this.setState({ visible: false }); }); } saveFormRef = (form) => { this.form = form; }render() {... const myForm= Form.create()(CrateNewItemFormOnModal);... return ( <div> <Button onClick={this.showModal}>Add</Button> <myForm visible={this.state.visible} onCancel={this.handleCancel} onCreate={this.handleCreate} ref={this.saveFormRef} /> </div> );}
In CrateNewItemFormOnModal component class I have a modal dialogue component as a parent and form component as a child:
export default class AddNewItemForm extends React.Component {render() { ... const { visible, onCancel, onCreate, form } = this.props; ... return ( <Modal title="Create new item" visible={visible} onOk={onCreate} onCancel={onCancel} okText="Create" > <Form> ... </Form> </Modal> );}