Reputation: 11475
I got a form like this
const SubtitleForm = ({ sub }) => {
const formik: any = useFormik({
initialValues: sub,
onSubmit: async (values) => {
const res = await update(values)
},
})
return (
<form className="subtitleFormComponent">
<input
className="subtitle"
autoComplete="off"
type="text"
name="name"
onChange={formik.handleChange}
value={formik.values.name}
/>
</form>
)
}
export default SubtitleForm
How can I trigger submit from outside this form / component ?
Upvotes: 0
Views: 4470
Reputation: 606
If you meant to have the submit button in a different component to the fields; I'd suggest to wrap both in the form. Then, you can use the useFormikContext
in the inputs to update the data, and in the submit button.
A POC of the idea: https://codesandbox.io/s/sharp-chebyshev-5nonm?file=/src/App.js
EDIT:
If someone need it, using useRef
will allow you to submit from outside the <Formik>
tag:
...
const formRef = useRef(null);
...
const handleSubmit = ()=> {
formRef.current?.handleSubmit();
}
...
<Formik
innerRef={formRef}
initialValues={sub}
onSubmit={...}
>
...
</Formik>
<button onClick={handleSubmit}>Submit</button>
Here's a demo: https://codesandbox.io/s/formik-submit-button-outside-the-form-fqcxrr?file=/src/App.js
Upvotes: 0