Disable submission on enter #3235
-
The form triggers the onSubmit function by pressing enter on any of the fields. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
This is an event which React gets from HTML. HTML forms naturally submit when the user presses enter anytime there is a submit button. You can either remove the One Formik-specific example would be to replace Formik's const MyForm = () => {
return <Formik {...formikProps}>
{({ handleSubmit }) =>
<form onSubmit={e => {
e.preventDefault();
// I made this up, you'll have to test this out. If you put together a codesandbox I can take a look.
// I added a catch here in case the user hits enter on the button itself
if (e.type !== "keydown" || (e.target && e.target.type === "submit")) {
handleSubmit(e);
}
}
} Alternatively you could instead create your own reusable const EnterBlockingForm: React.FC = (props) => {
const { handleSubmit } = useFormikContext();
return <form
onSubmit={e => {
e.preventDefault();
// I made this up, you'll have to test this out. If you put together a codesandbox I can take a look.
// I added a catch here in case the user hits enter on the button itself
if (e.type !== "keydown" || (e.target && e.target.type === "submit")) {
handleSubmit(e);
}
}
>
{props.children}
</form>
}
const MyForm = () => {
return <Formik {...formikProps}>
<EnterBlockingForm>
<Field name="firstName" />
<button type="submit">Submit</button>
</EnterBlockingForm>
</Formik>
} |
Beta Was this translation helpful? Give feedback.
This is an event which React gets from HTML. HTML forms naturally submit when the user presses enter anytime there is a submit button. You can either remove the
"<button type="submit" />
and replace it with a non-submit button which triggers formik.handleSubmit(event) on click, or follow any of the other recommendations on various StackOverflow issues.One Formik-specific example would be to replace Formik's
<Form />
helper component with a regular form, and replace its onSubmit: