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

1

10

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?

Nauseating answered 19/4, 2017 at 7:10 Comment(1)
Possible cublicate : #11921710Absenteeism
S
13

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 :)

Siesta answered 19/4, 2017 at 7:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.