React | Should onSubmit Go on the <form> or the <button>?

1 min read
1. Using onSubmit on the
- Put
onSubmit
on the<form>
. - Use
type="submit"
on the button. - Call
e.preventDefault()
in your handler if needed.
<form onSubmit={handleSubmit}>
<input type="text" />
<button type="submit">Send</button>
</form>
This approach handles submission for the entire form, including when the user presses the Enter key, which improves keyboard accessibility.
2. Using onClick on the
- Works, but not ideal for forms.
- Still use type="submit" for accessibility.
<form>
<input type="text" />
<button type="submit" onClick={handleSubmit}>Send</button>
</form>
This approach only responds to mouse clicks or taps on the button itself, and may not handle keyboard submission (e.g. pressing Enter) properly, which can negatively affect accessibility.
0
Subscribe to my newsletter
Read articles from Valencia Miyeon Jang directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
