Home » Prevent Page Reload on Form Submit in React

Prevent Page Reload on Form Submit in React

prevent page reload on form submit in react js

In today’s article, we will discuss how to prevent page reload on form submit in React JS. In web development, form submissions are a prevalent task and usually, we might notice that when we submit the form the web page tends to reload. 

In this tutorial, we will look at a few ways to prevent the web page from reloading on form submission.

Use preventDefault() in Form onSubmit Event To Prevent Page Reload

When the user clicks on the form submit button, it is a default behavior of the browser to reload the web page. And sometimes we just don’t want this kind of behavior to happen. To prevent the web page from reloading, we can use the preventDefault() method of the javascript Event interface.

import "./App.css";
 
function App() {
  return (
    <div>
      <form onSubmit={(event) => event.preventDefault()}>
        <input type="text" name="username"  />
        <input type="password" name="password"  />
        <input type="submit" value="Submit" />
      </form>
    </div>
  );
}
 
export default App;

In the above code, we are using the preventDefault() method inside the onSubmit event callback to prevent page reload. The onSubmit event will be triggered whenever the form is submitted. 

We can write our form validation logic like username and password validation after the preventDefault() method is called. 

Using the preventDefault() method allows us to implement our own way of form submission like we can show a custom loader until the form is submitted successfully and we can display a success message to the user after the form is submitted.

Using The Submit Button’s onClick Event

Instead of using the preventDefault() method inside the form onSubmit event callback. We can also use the submit button onClick event handler, like this:

<form>
 <input type="text" name="username" />
 <input type="password" name="password" />
 <button type="submit" onClick={(event) => event.preventDefault()}>
   Submit
 </button>
</form>

Conclusion

In this blog post, we have discussed how to use the preventDefault() method to prevent the web page from reloading.

While creating our forms we need to consider the user experience. To provide a better user experience we can show a loader when the form submit button is clicked, show a success message when the form is submitted successfully, etc.

Leave a Reply

Your email address will not be published.