Can you make a form that submits without refreshing the entire page?

Question

In the context of this lesson, can you make a form that submits without refreshing the entire page?

Answer

Yes, you can do this utilizing some methods in JavaScript.

React forms are helpful when we want to re-send a form on each change, without having to send it again each time. However, if we need to actually submit and pass the information through to somewhere else, like a database, we will need to submit a <form> element which requires a page refresh. To prevent this refresh, we can use the preventDefault() method in JavaScript within the function that is invoked on the form submission.

For example,

// Function that runs when the submit button is pressed
handleSubmit(e) {
  // Prevents the default behavior, which includes page refreshing
  e.preventDefault();

  // Rest of the code for the function
  ... 
}
1 Like

Hi there,

Whilst preventdefault() is very useful to prevent unnecessary form ‘submits’, there is a way apparently without using JS. Well, JS is used but mostly for displaying error messages. Most likely, a new feature introduced in HTML!

Client-side form validation - Learn web development | MDN (mozilla.org)

Have a look!