DEV Community

Cover image for Why Should You Use OnSubmit() Instead Of OnClick() Event Listener
Wasim A Pinjari
Wasim A Pinjari

Posted on • Updated on • Originally published at wasimapinjari.netlify.app

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

You can add 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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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 HTML form gets disable if you add 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.

Follow me: @wasimapinjari

Links: wasimapinjari.bio.link

Top comments (0)