Prevent Default and Form Events

Prevent Default and Form Events

·

2 min read

And the default behavior by the browser is that if a form is submitted with a button instead of a form, a HTTP request is sent to the server serving this website.

That happens automatically. The browser does this automatically. It sends an HTTP request to the server, which is serving this website. The problem with that is that here, we don't really have a server that wants to do anything with that request, we just have a static server that serves our JavaScript and HTML files. So we don't want this request to be sent, and hence on this event object, which we get automatically passed into this function since we've bounded to on submit, on this event object, we can call prevent default to tell the browser to not do that default behavior, to not send this HTTP request, and instead to do nothing.

And we need to do that because if that HTTP request would be sent, it would lead to the page being reloaded in the end, and we definitely don't want that, because that would restart the entire react application, we would lose all our state, and we would definitely not have the behavior we want. So that's important.

Then as a next step, now that we can guarantee that the page won't be reloaded and the app won't be restarted, we can console log the entered name.