Replies: 2 comments 1 reply
-
I've faced the same problem and came up with a workaround. const SomeForm = ({submitRef, handleSubmit, ...etc}) => {
return (
<Form onSubmit={handleSubmit}>
...
<input ref={submitRef} hidden type="submit" />
...
</Form>
);
} Then you can force the form to submit with submitRef: const submitRef = useRef();
const submit = () => {
submitRef.current.click();
};
return (<SomeForm submitRef={submitRef} .../>) For other cases bugfix for withFormik is still required. |
Beta Was this translation helpful? Give feedback.
-
This is me from the future informing my past self, as well as anyone else who finds this relevant. TLDR drop import React, { forwardRef, useRef } from "react"
import { connect } from "react-redux"
import * as Yup from "yup"
import { Formik, Field, Form, ErrorMessage, FormikProps, FormikBag, FormikHelpers } from 'formik';
type FixMe = any // for example purposes only.
interface FormValues {
firstName: string
lastName: string
}
const mapState = ({userProfile}:FixMe) => ({userProfile})
const mapDispatch = { }
const connectorWithRef = connect(mapState, mapDispatch, null, {forwardRef: true})
const ValidationSchema = Yup.object({
firstName: Yup.string()
.max(15, 'Must be 15 characters or less')
.required('Required'),
lastName: Yup.string()
.max(20, 'Must be 20 characters or less')
.required('Required'),
})
const ParentContainer = () => {
const formRef = useRef<FixMe>() // Again, FixMe type is for demonstration purposes. This is a React.MutableRefObject
const handleSubmitForm = () => {
console.log(formRef.current)
formRef.current.handleSubmit(formRef.current.values)
}
return (
<div>
<ChildFormikComponent ref={formRef}/>
<button onClick={handleSubmitForm}>parent button</button>
</div>
)
}
const ChildFormikComponent = connectorWithRef(
forwardRef((props, ref) => {
return (
<Formik
innerRef={ref as React.MutableRefObject<FormikProps<FormValues>>}
initialValues={{ firstName: '', lastName: ''}}
validationSchema={ValidationSchema}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 400);
}}>
<Form style={{display: "flex", flexDirection: "column"}}>
<label htmlFor="firstName">First Name</label>
<Field name="firstName" type="text" />
<ErrorMessage name="firstName" />
<label htmlFor="lastName">Last Name</label>
<Field name="lastName" type="text" />
<ErrorMessage name="lastName" />
<button hidden type="submit">Submit</button>
</Form>
</Formik>
)
}))
export default ParentContainer Important takeaways:
|
Beta Was this translation helpful? Give feedback.
-
I want to inject a ref in my formik form. However withFormik obfuscate the forwarding of the reference. This is an excerpt from my code. Anyone knows the right recipe?
Beta Was this translation helpful? Give feedback.
All reactions