How do you prevent a form from reloading the page when it is submitted in React?
Short answer
By default, submitting an HTML form reloads the entire page. In React, you call preventDefault on the submit event inside your onSubmit handler, which stops the browser's default reload behavior and lets your JavaScript code handle the submission instead.
Advertisement
AModel answer
By default, submitting an HTML form reloads the entire page. In React, you call preventDefault on the submit event inside your onSubmit handler, which stops the browser's default reload behavior and lets your JavaScript code handle the submission instead.
function ContactForm() {
function handleSubmit(event) {
event.preventDefault();
console.log('Form submitted without reloading the page');
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Send</button>
</form>
);
}Real-world example
A contact form smoothly shows a thank you message after submission, without the jarring full page reload that would normally happen if preventDefault had not been called on the submit event.
Likely follow-ups
- What happens if you forget to call preventDefault inside your submit handler?
- Is there a difference in behavior between an onClick handler on the button versus an onSubmit handler on the form?
Related topics