0

I have a simple react form with an onSubmit handler. Inside the handler a post request is made. It's like this

const handleSubmit = async (e) => {
    e.preventDefault();
    const response = await fetch('...', method post, body ... etc)
    setStatus(await response.text())
}

The problem I'm having is that my function is basically still triggered by the enter button so it makes a post request. I want this to only happen when someone actually clicks the button. I thought maybe I could do this by filtering on the event keyCode but I can't find it.

Blackfrwhite
  • 39
  • 2
  • 10
  • _“but I can't find it”_ - are you sure you actually _searched_ in the first place? https://stackoverflow.com/questions/895171/prevent-users-from-submitting-a-form-by-hitting-enter – CBroe Mar 02 '21 at 15:21
  • Ofcourse but none of the answers in there worked. Most are jquery based solutions. – Blackfrwhite Mar 02 '21 at 15:23
  • So what, that changes very little about the _principle_. – CBroe Mar 02 '21 at 15:24

1 Answers1

0

you have to use onKeyPress props, e.g:

const handleKeyPress = (event)  = {
    if (event.which === 13) {
      event.preventDefault();
    }
},

return (
    <form onKeyPress={handleKeyPress}...
)

NOTE: The submit event is executed (when onSubmit is also executed) when you use onSubmit, So it is too late at that time to prevent the default action.

PS-PARSA
  • 932
  • 5
  • 15