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