Why Should You Use OnSubmit() Instead Of OnClick() Event Listener
Let's say this is my React form component:
function Form() {
function handleSubmit(e) {
e.preventDefault();
}
return (
<form onSubmit={handleSubmit}>
<input type="text" placeholder="Type anything..."/>
<button>Submit</button>
</form>
);
}
You can add an onClick() event listener on the button instead of onSubmit on the form like so:
function Form() {
function handleSubmit(e) {
e.preventDefault();
}
return (
<form>
<input type="text" placeholder="Type anything..."/>
<button onClick={handleSubmit}>Submit</button>
</form>
);
}
Nothing will seem to change really. Everything is working the same. But there is a slight difference.
To understand the difference you need to know in HTML you can press Enter button on your keyboard to submit the form. If I type something in my input and press Enter the form will be submitted.
This functionality of the HTML form gets disabled if you add an onClick() event listener to your submit button.
If that's what you're looking for then feel free to use onClick() event listener to your submit button.
Thanks for reading!
Follow me: @wasimapinjari
Links: wasimapinjari.bio.link