<form>
<input />
<button
onClick={e => {
e.preventDefault();
alert("clicked");
}}
>
click
</button>
</form>
If I move the onClick handler to form's onSubmit, I will get the exact same behavior.
Most answers I googled suggested that the difference is onClick will not react to submitting form via return key press but that's not true as seen in the codesandbox example.
When will they behave differently, apart from when dealing with DOM manipulation/event simulation?
Fundamentally, this is up to the browser. Some browsers might call a submit button's onClick when the form is submitted by pressing the return key, but the standard doesn't mandate this. Others might only call onClick when return is pressed if the submit button is selected. Others might not fire it unless the button is manually clicked.
If you want the best portability, use onSubmit for what it's designed for: to detect form submission.
The other main difference is the target for the event.
Note that the submit event fires on the <form> element itself, and not on any <button> or <input type="submit"> inside it. (Forms are submitted, not buttons.)
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With