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.