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} />
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…