82

Current Behavior

<Formik
    isInitialValid
    initialValues={{ first_name: 'Test', email: 'test@mail.com' }}
    validate={validate}
    ref={node => (this.form = node)}
    onSubmitCallback={this.onSubmitCallback}
    render={formProps => {
        const fieldProps = { formProps, margin: 'normal', fullWidth: true, };
        const {values} = formProps;
        return (
            <Fragment>
                <form noValidate>
                    <TextField
                        {...fieldProps}
                        required
                        autoFocus
                        value={values.first_name}
                        type="text"
                        name="first_name"

                    />

                    <TextField
                        {...fieldProps}
                        name="last_name"
                        type="text"
                    />

                    <TextField
                        {...fieldProps}
                        required
                        name="email"
                        type="email"
                        value={values.email}

                    />
                </form>
                <Button onClick={this.onClick}>Login</Button>
            </Fragment>
        );
    }}
/>

I'm trying this solution https://github.com/jaredpalmer/formik/issues/73#issuecomment-317169770 but it always return me Uncaught TypeError: _this.props.onSubmit is not a function

When I tried to console.log(this.form) there is submitForm function.

Any solution guys?


- Formik Version: latest - React Version: v16 - OS: Mac OS

ssuhat
  • 7,387
  • 18
  • 61
  • 116

12 Answers12

111

Just for anyone wondering what's the solution via React hooks :

Formik 2.x, as explained in this answer

// import this in the related component
import { useFormikContext } from 'formik';

// Then inside the component body
const { submitForm } = useFormikContext();

const handleSubmit = () => {
  submitForm();
}

Keep in mind that solution only works for components inside a Formik component as this uses the context API. If for some reason you'd like to manually submit from an external component, or from the component the Formik is actually used from, you can actually still use the innerRef prop.

TLDR ; This context answers works like a charm if the component that you're submitting from is a child of a <Formik> or withFormik() component, otherwise, use the innerRef answer below.

Formik 1.5.x+

// Attach this to your <Formik>
const formRef = useRef()

const handleSubmit = () => {
  if (formRef.current) {
    formRef.current.handleSubmit()
  }
}

// Render
<Formik innerRef={formRef} />
Eric Martin
  • 2,247
  • 1
  • 16
  • 16
40

You can bind formikProps.submitForm (Formik's programatic submit) to a parent component and then trigger submission from the parent:

import React from 'react';
import { Formik } from 'formik';

class MyForm extends React.Component {
    render() {
        const { bindSubmitForm } = this.props;
        return (
            <Formik
                initialValues={{ a: '' }}
                onSubmit={(values, { setSubmitting }) => {
                    console.log({ values });
                    setSubmitting(false);
                }}
            >
                {(formikProps) => {
                    const { values, handleChange, handleBlur, handleSubmit } = formikProps;

                    // bind the submission handler remotely
                    bindSubmitForm(formikProps.submitForm);

                    return (
                        <form noValidate onSubmit={handleSubmit}>
                            <input type="text" name="a" value={values.a} onChange={handleChange} onBlur={handleBlur} />
                        </form>
                    )
                }}
            </Formik>
        )
    }
}

class MyApp extends React.Component {

    // will hold access to formikProps.submitForm, to trigger form submission outside of the form
    submitMyForm = null;

    handleSubmitMyForm = (e) => {
        if (this.submitMyForm) {
            this.submitMyForm(e);
        }
    };
    bindSubmitForm = (submitForm) => {
        this.submitMyForm = submitForm;
    };
    render() {
        return (
            <div>
                <button onClick={this.handleSubmitMyForm}>Submit from outside</button>
                <MyForm bindSubmitForm={this.bindSubmitForm} />
            </div>
        )
    }
}

export default MyApp;
Elise Chant
  • 5,048
  • 3
  • 29
  • 36
22

The best solution I've found is described here https://stackoverflow.com/a/53573760

Copying the answer here:

Add "id" attribute to your form: id='my-form'

class CustomForm extends Component {
    render() {
        return (
             <form id='my-form' onSubmit={alert('Form submitted!')}>
                // Form Inputs go here    
             </form>
        );
    }
}

Then add the same Id to the "form" attribute of the target button outside of the form:

<button form='my-form' type="submit">Outside Button</button>

Now, the 'Outside Button' button will be absolutely equivalent as if it is inside the form.

Note: This is not supported by IE11.

Yevhen
  • 329
  • 2
  • 6
21

I just had the same issue and found a very easy solution for it hope this helps:

The issue can be solved with plain html. If you put an id tag on your form then you can target it with your button using the button's form tag.

example:

      <button type="submit" form="form1">
        Save
      </button>
      <form onSubmit={handleSubmit} id="form1">
           ....
      </form>

You can place the form and the button anywhere even separate.

This button will then trigger the forms submit functionality and formik will capture that continue the process as usual. (as long as the form is rendered on screen while the button is rendered then this will work no matter where the form and the button are located)

5

If you convert your class component to a functional component, the custom hook useFormikContext provide a way to use submit anywhere down the tree:

   const { values, submitForm } = useFormikContext();

PS: this only for those who don't really need to call submit outside the Formik Component, so instead of using a ref you can put your Formik component at a higher level in the component tree, and use the custom hook useFormikContext, but if really need to submit from outside Formik you'll have to use a useRef .

<Formik innerRef={formikRef} />

https://formik.org/docs/api/useFormikContext

ZEE
  • 5,669
  • 4
  • 35
  • 53
4

In 2021, using 16.13.1, this way worked for me to satisfy several requirements:

  • The submit/reset buttons cannot be nested within the <Formik> element. Note, if you can do this then you should use the useFormikContext answer because it is simpler than mine. (Mine will allow you to change which form is being submitted (I have one app bar but multiple forms the user can navigate to).
  • The external submit/reset buttons must be able to submit and reset the Formik form.
  • The external submit/reset buttons must appear disabled until the form is dirty (the external component must be able to observe the Formik form's dirty state.)

Here's what I came up with: I created a new context provider dedicated to holding some helpful Formik stuff to link my two external components which are in different nested branches of the app (A global app bar and a form somewhere else, deeper in a page view – in fact, I need the submit/reset buttons to adapt to different forms the user has navigated to, not just one; not just one <Formik> element, but only one at a time).

The following examples use TypeScript but if you only know javascript just ignore the stuff after colons and it's the same in JS.

You place <FormContextProvider> high enough in your app that it wraps both of the disparate components that need to have access to Formik stuff. Simplified example:

<FormContextProvider>
  <MyAppBar />
  <MyPageWithAForm />
</FormContextProvider>

Here's FormContextProvider:

import React, { MutableRefObject, useRef, useState } from 'react'
import { FormikProps, FormikValues } from 'formik'

export interface ContextProps {
  formikFormRef: MutableRefObject<FormikProps<FormikValues>>
  forceUpdate: () => void
}

/**
 * Used to connect up buttons in the AppBar to a Formik form elsewhere in the app
 */
export const FormContext = React.createContext<Partial<ContextProps>>({})

// https://github.com/deeppatel234/react-context-devtool
FormContext.displayName = 'FormContext'

interface ProviderProps {}

export const FormContextProvider: React.FC<ProviderProps> = ({ children }) => {
  // Note, can't add specific TS form values to useRef here because the form will change from page to page.
  const formikFormRef = useRef<FormikProps<FormikValues>>(null)
  const [refresher, setRefresher] = useState<number>(0)

  const store: ContextProps = {
    formikFormRef,
    // workaround to allow components to observe the ref changes like formikFormRef.current.dirty
    forceUpdate: () => setRefresher(refresher + 1),
  }

  return <FormContext.Provider value={store}>{children}</FormContext.Provider>
}

In the component that renders the <Formik> element, I add this line:

const { formikFormRef } = useContext(FormContext)

In the same component, I add this attribute to the <Formik> element:

innerRef={formikFormRef}

In the same component, the first thing nested under the <Formik> element is this (importantly, note the addition of the <FormContextRefreshConduit /> line).

<Formik
  innerRef={formikFormRef}
  initialValues={initialValues}
  ...
>
  {({ submitForm, isSubmitting, initialValues, values, setErrors, errors, resetForm, dirty }) => (
    <Form>
      <FormContextRefreshConduit />
      ...

In my component that contains the submit/reset buttons, I have the following. Note the use of formikFormRef

export const MyAppBar: React.FC<Props> = ({}) => {
  const { formikFormRef } = useContext(FormContext)
  
  const dirty = formikFormRef.current?.dirty

  return (
    <>
      <AppButton
        onClick={formikFormRef.current?.resetForm}
        disabled={!dirty}
      >
        Revert
      </AppButton>
      <AppButton
        onClick={formikFormRef.current?.submitForm}
        disabled={!dirty}
      >
        Save
      </AppButton>
    </>
  )
}

The ref is useful for calling Formik methods but is not normally able to be observed for its dirty property (react won't trigger a re-render for this change). FormContextRefreshConduit together with forceUpdate are a viable workaround.

Thank you, I took inspiration from the other answers to find a way to meet all of my own requirements.

ABCD.ca
  • 2,365
  • 3
  • 32
  • 24
  • great call on the `forceUpdate` addition. That's the catch with `innerRef` - it won't trigger rerenders in parent components. Your distinction between using it to expose Formik methods (e.g. `submitForm` or `resetForm`) vs. using it to observe state (e.g. `dirty` or `isSubmitting`) is spot on. Very helpful. – Brock Klein Feb 21 '22 at 19:33
  • @ABCD.ca, when your Formik renders, it calls its rendering function, which renders which uses `FormContext` to call `forceUpdate` which changes the state of the `FormContext`. How do you not get `Warning: Cannot update a component (FormContextProvider) while rendering a different component (Formik).` – THX-1138 Aug 07 '22 at 03:05
  • @THX-1138 Sorry, I don't know but it doesn't give me that error – something about it being in a different scope seems to help – ABCD.ca Aug 09 '22 at 17:27
  • @ABCD.ca is there a way to get a runnable link/code for your method? I'm following a similar approach but getting the error message I quoted above in the console (at run-time). – THX-1138 Aug 09 '22 at 19:23
1

If you're using withFormik, this worked for me:

  const handleSubmitThroughRef = () => {
    newFormRef.current.dispatchEvent(
      new Event("submit", { cancelable: true, bubbles: true })
    );
  };

Just put a regular react ref on your form:

  <form
        ref={newFormRef}
        
        onSubmit={handleSubmit}
      >
Tony Jara
  • 69
  • 2
0

found the culprit.

There are no longer onSubmitCallback on Formik props. Should change it to onSubmit

ssuhat
  • 7,387
  • 18
  • 61
  • 116
0

You can try it

const submitForm = ({ values, setSubmitting }) =>{//...do something here}

<Formik onSubmit={(values, {setSubmitting })=> submitForm({values, setSubmitting})> {()=>(//...do something here)}

0

Another simple approach is to useState and pass prop to the child formik component. There you can setState with a useEffect hook.

const ParentComponent = () => {
  const [submitFunc, setSubmitFunc] = useState()
  return <ChildComponent setSubmitFunc={setSubmitFunc}>
}

const ChildComponent= ({ handleSubmit, setSubmitFunc }) => {
   useEffect(() => {
     if (handleSubmit) setSubmitFunc(() => handleSubmit)
   }, [handleSubmit, setSubmitFunc])

   return <></>
 }
0

I've implemented this in a React Class component, step by step :

1 - I've declared a "ref" variable to keep reference of form object, (useRef is valid only in function components so I've coded as below by using React.createRef() function )

constructor(props) {
  super(props);
  this.visitFormRef = React.createRef();
}

2 - There is an "innerRef" feature on formik forms, so I've assigned the ref variable above to it :

<Formik 
    initialValues={initialValues}
    onSubmit={(values) => onSubmit(values)}
    validationSchema={validationSchema}
    enableReinitialize={true}
    innerRef={this.visitFormRef}  //<<--here
>

3- To trigger the submit event of the form, from somewhere out of the form I have declared a function below :

triggerFormSubmit = () => {
    
    if (this.visitFormRef.current) 
        this.visitFormRef.current.handleSubmit();
}

4- And finally I've called the function above from an external button :

<Button onClick={() => this.triggerFormSubmit()} />

Note not to confuse : onSubmit(values) function which assined to the formik form, is still exists and it's getting the from values. We've just triggered it from an external button here

Bulent Balci
  • 644
  • 5
  • 11
0

Here is how I achieved mine by using ref to simulate an internal hidden submit button being clicked when the user clicks the external submit button.

const hiddenInnerSubmitFormRef = useRef(null);

const handleExternalButtonClick = () => {
  hiddenInnerSubmitFormRef.current.click();
}

return (
<>
  {/* External Button */}
  <button onClick={handleExternalButtonClick}>
   External Submit
  </button>

  <Formik onSubmit={values => console.log(values)}>
   {() => (
     <Form>

      {/* Hide Button /*}
      <button type="submit" ref={hiddenInnerSubmitFormRef} className="hidden">
        Submit
      </button>
     </Form>
   )}
  </Formik>
 </>
)
Idris
  • 558
  • 7
  • 29
  • For functional component, this answer will trigger error: `Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?` so better use the other solution in this page: https://stackoverflow.com/a/58223758/1537413 – Dika Aug 30 '22 at 06:29
  • @Dika This was the exact method I used and it didn't trigger any error – Idris Aug 30 '22 at 16:49
  • 2 possibilities: either you don't use functional component, or you use older react version than mine – Dika Sep 01 '22 at 04:23