How to submit a form using Enter key in react.js?

Change <button type="button" to <button type="submit". Remove the onClick. Instead do <form className="commentForm" onSubmit={onFormSubmit}>. This should catch clicking the button and pressing the return key.

const onFormSubmit = e => {
  e.preventDefault();
  // send state to server with e.g. `window.fetch`
}

...

<form onSubmit={onFormSubmit}>
  ...
  <button type="submit">Submit</button>
</form>

Full example without any silly form libraries:

function LoginForm() {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [submitting, setSubmitting] = useState('')
  const [formError, setFormError] = useState('')

  const onFormSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    try {
      e.preventDefault();
      setFormError('')
      setSubmitting(true)
      await fetch(/*POST email + password*/)
    } catch (err: any) {
      console.error(err)
      setFormError(err.toString())
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <form onSubmit={onFormSubmit}>
      <input type="email" autoComplete="email" value={email} onChange={e => setEmail(e.currentTarget.value)} required />
      <input type="password" autoComplete="current-password" value={password} onChange={e => setPassword(e.currentTarget.value)} required />
      {Boolean(formError) &&
        <div className="form-error">{formError}</div>
      }
      <button type="submit" disabled={submitting}>Login</button>
    </form>
  )
}

P.S. Remember that any buttons in your form which should not submit the form should explicitly have type="button".

Leave a Comment