reactjs - Formik form does not fire submit on return key press
The best way that I found to solve this scenery is to call handleSubmit() method inside onKeyDown event of HTML Form Element that is child of Formik.
<Formik
initialValues={{
login: '',
senha: ''
}}
onSubmit={(values, { setErrors }) => {
this.submitSignin(values, setErrors);
}}
>
{props => {
const {
values,
handleChange,
handleBlur,
handleSubmit,
} = props;
return (
<form
onSubmit={handleSubmit}
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleSubmit();
}
}}>
<input
id="login"
value={values.login}
onChange={handleChange}
onBlur={handleBlur} />
<input
id="senha"
value={values.senha}
onChange={handleChange}
onBlur={handleBlur} />
</form>
}
</Formik>
I was able to solve this on your Codesandbox by removing the {...rest}
props spread you were applying in the SimpleInput component. This added some funky attributes that seemed to be interfering with the standard form field behavior.
You can see the proper submit-on-enter behavior here: https://codesandbox.io/s/dark-star-r0liq
In my own code, I am using a standard HTML <form>
instead of the Formik <Form>
, so when I ran into this issue, I had to ensure my submit button had both type="submit"
attribute, as well as the onClick
handler hooked up to Formik's handleSubmit
method. Then the submit-on-enter behavior started working.
<button
onClick={formProps.handleSubmit}
type="submit"
/>
Related official repo issue: https://github.com/jaredpalmer/formik/issues/1418
Maybe try using the children prop with Formik as shown here: https://jaredpalmer.com/formik/docs/api/formik#children-reactreactnode-props-formikprops-values-reactnode
And remove the form element wrapping the form. Or disable the default behavior of the form. That's what's intercepting the enter keypress behavior.