Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does event.preventDefault() do exactly inside a submit button function?

Learning React and I know this question isn't part of it but I've always wondered what the preventDefault part does:

  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
  }

When I opened the example in a page and removed the preventDefault, the page just doesn't refresh when I hit submit. So does that mean the default behavior of a submit button on click is to make a send the form data somewhere and then redirect the current page to somewhere else? By having preventDefault, this prevents it from happening? Is this event a Dom event?

like image 460
stackjlei Avatar asked Apr 19 '17 07:04

stackjlei


1 Answers

event.preventDefault() basically prevents event to fire. In the case of submit event. event.preventDefault() will prevent your form to submit.

We normally prevent submit behaviour to check some validation before submitting the form or we need to change values of our input fields or we want to submit using ajax calls. For this purpose, we prevent form to be submitted by using:

event.preventDefault();
// Here comes our custom logic

This is a good read for your question. Hope this helps :)

like image 180
Muhammad Qasim Avatar answered Oct 11 '22 13:10

Muhammad Qasim