Categories
React Answers

How to Prevent Basic React Form Submit From Refreshing the Entire Page?

Spread the love

Sometimes, we want to prevent basic React form submit from refreshing the entire page.

In this article, we’ll look at how to prevent basic React form submit from refreshing the entire page.

Prevent Basic React Form Submit From Refreshing the Entire Page

To prevent basic React form submit from refreshing the entire page, we call e.preventDefault. in the submit event handler.

For instance, we write:

import React from "react";

export default function App() {
  const onSubmit = (e) => {
    e.preventDefault();
    console.log("refresh prevented");
  };

  return (
    <div>
      <form onSubmit={onSubmit}>
        <button type="submit">submit</button>
      </form>
    </div>
  );
}

to create the onSubmit function that’s set as the value of the onSubmit prop.

In the function, we call e.preventDefault to prevent the default submission behavior, which is to do server side form submission which refreshes the whole page.

We have a submit button in the form to do the form submission.

Therefore, instead of seeing the page refresh when we click submit, we should see the 'refresh prevented' string logged in the console instead.

Conclusion

To prevent basic React form submit from refreshing the entire page, we call e.preventDefault. in the submit event handler.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

3 replies on “How to Prevent Basic React Form Submit From Refreshing the Entire Page?”

Sir when I click on save button, I want my data without reload or refresh the page in reactjs.

Leave a Reply

Your email address will not be published. Required fields are marked *