How to Handle Form Submit in React: Simple Guide
onSubmit event handler to the <form> element and calling event.preventDefault() inside the handler to stop the page from reloading. Then, process the form data as needed within that handler function.Why This Happens
When you submit a form in React without preventing the default behavior, the browser reloads the page. This happens because HTML forms naturally try to send data and refresh the page on submit.
import React from 'react'; function MyForm() { function handleSubmit(event) { alert('Form submitted'); } return ( <form onSubmit={handleSubmit}> <button type="submit">Submit</button> </form> ); } export default MyForm;
The Fix
To fix this, call event.preventDefault() inside the submit handler. This stops the page reload and lets you handle the form data smoothly.
import React from 'react'; function MyForm() { function handleSubmit(event) { event.preventDefault(); alert('Form submitted without page reload'); } return ( <form onSubmit={handleSubmit}> <button type="submit">Submit</button> </form> ); } export default MyForm;
Prevention
Always use event.preventDefault() in form submit handlers to avoid unwanted page reloads. Use controlled components to manage form inputs and keep state updated. Use descriptive function names like handleSubmit and keep your form logic inside this handler for clarity.
Enable linting rules like react-hooks/rules-of-hooks and jsx-a11y/no-noninteractive-element-interactions to catch common mistakes early.
Related Errors
Common related errors include:
- Not binding
thisin class components for handlers (legacy pattern). - Using
onClickon the submit button withoutonSubmiton the form, which can miss keyboard submits. - Forgetting to set
type="submit"on the button, so the form does not submit.
Key Takeaways
onSubmit on the <form> element to handle form submission in React.event.preventDefault() inside the submit handler to stop page reload.handleSubmit, for readability.onClick on buttons alone for form submission to support accessibility.