How do I get the value of the pressed button on a Formik form?

Viewed 2448

When using Formik in a React application, with a form that has multiple buttons defined like this:

<button type="submit" name="action" value="unlock">Unlock account</button>
<button type="submit" name="action" value="delete">Delete account</button>

How do I obtain the name and/or value of the pressed button?

I did tried adding the field action to my initialValues, but it remains blank.

3 Answers

I found a workaround which is to define my buttons this way:

<button type="submit" onClick={() => setFieldValue("action", "unlock")}>unlock</button>
<button type="submit" onClick={() => setFieldValue("action", "delete")}>delete</button>

and then on Formik's onSubmit callback, I check and reset the action field.

Here is a way to wrap onSubmit in the form and use the event.submitter property to get a reference to the button that was pressed, and then set this into Formik before finally handling the form.

<Formik
  initialValues={{}}
  onSubmit={async values => {
    console.log('onSubmit', values);
  }}
>
  {({ handleSubmit, setFieldValue }) => (
    <form
      onSubmit={jsEvent => {
        // This is a bit of a hack to copy the name and value of
        // the submitter into the Formik form
        const { name, value } = jsEvent.nativeEvent.submitter;
        setFieldValue(name, value);

        return handleSubmit(jsEvent);
      }}
    >
      ...
    </form>
  )}
</Formik>
                <FieldArray name='_action' className='row'>
                    {
                        (props) => {
                            const { field, form, meta } = props
                            console.log("test", props)

                            return (
                                <div>
                                    <button type="submit" onClick={() => form.setFieldValue("_action", "unlock")}>unlock</button>
                                    <button type="submit" onClick={() => form.setFieldValue("_action", "delete")}>delete</button>
                                </div>
                            )
                        }
                    }
                </FieldArray>

Related