Rob Bauer
Rob Bauer

Reputation: 857

How to disable form submit on enter with useFormik?

I am building a form using React, Typescript and Formik. The form has three inputs. I want to prevent the form from submitting when the user presses enter in the input fields.

My first approach was using the event.preventDefault() statement, but that didn't work. Then I found this solution here on stackoverflow, but in this solution the Formik component is used and not the useFormik hook.

So I wounder how to disable form submit on enter with useFormik?

Upvotes: 0

Views: 3567

Answers (3)

LS-MTR
LS-MTR

Reputation: 11

we can prevent it on the form:

<Form onKeyDown={(e) => {
    if (e.key === 'Enter') {
      e.preventDefault();
    }
  }}
>

Upvotes: 1

Ajith S Nair
Ajith S Nair

Reputation: 11

<button type='button'>Submit</button>

type='button'

By using this, pressing enter would not trigger the form onSubmit .

Upvotes: 1

Antoine Gagnon
Antoine Gagnon

Reputation: 982

The useFormik hook provides a handleSubmit methods which handles that, pass it to your form onSubmit prop.

...
const fomrik = useFormik(...);

return (
  <form onSubmit={formik.handleSubmit}>
...

Upvotes: 1

Related Questions