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