humptydumpty
humptydumpty

Reputation: 143

How to have multiple submit handlers on a page using Formik?

I have a page that's split into two parts: a few fields and button to submit/validate the top half and some fields and a button to submit/validate the bottom half. However, I didn't see in the documentation how this is done?

Something like this:

<Formik
    initialValues={{
        email: '[email protected]',
        password: '',
        
        address1: '',
        address2: '',
    }}

    handleFirstBtn={ values => {
    }}

    handleSecondtBtn={ values => {
    }}
>
    <Form>
        <div>
            <Field name="email" type="text" />
            <Field name="password" type="password" />        
            <button type="button" onClick={this.handleFirstBtn}>Submit</button>
            
            <Field name="address1" type="text" />
            <Field name="address2" type="text" />        
            <button type="button" onClick={this.handleSecondtBtn}>Submit</button>
        </div>
    </Form>

</Formik>

Upvotes: 1

Views: 5161

Answers (1)

Pavan Kalyan
Pavan Kalyan

Reputation: 407

class Demo extends React.Component {

Form1Callback = (values) => {
    console.log('formcallback1', values);
}

Form2Callback = (values) => {
    console.log('formcallback2', values);
}

render() {
    return (
        <div>
            <h2>Formik Demo</h2>
            <h3>form1</h3>
            <Form1 submit1={this.Form1Callback} /><br/>
            <h3>form2</h3>
            <Form2 submit2={this.Form2Callback} />

        </div>
    )
 }
 }


  const Form1 = (props) => {
 return (
    <div>
        <Formik
        initialValues={{email1:'',password1:'',}}
        onSubmit={(values)=>{
           props.submit1(values);
        }}>
            <Form>
                <Field type="email" name="email1" /><br />
                <Field type="password" name="password1" /><br />
                <button type="submit" >
                    Submit
                     </button><br />
            </Form>
        </Formik>
    </div>
 )
 }


 const Form2 = (props) => {
return (
    <div>
        <Formik
        initialValues={{email2:'',password2:'',}}
        onSubmit={(values)=>{
            props.submit2(values);
        }}
        >
            
            <Form>
                <Field type="email" name="email1" /><br />
                <Field type="password" name="password1" /><br />
                <button type="submit" >
                    Submit
                     </button><br />
            </Form>
        </Formik>
    </div>
 )
 }

well here is a POC for your issue. This is working as per your requirement

Upvotes: 2

Related Questions