How to Handle onSubmit Event in React: Simple Fix and Best Practices
onSubmit event by passing a function to the form's onSubmit attribute and calling event.preventDefault() inside that function to stop the page from reloading. This lets you control what happens when the form is submitted, like reading input values or sending data.Why This Happens
When you add an onSubmit handler in React but forget to prevent the default browser behavior, the page reloads on form submission. This happens because HTML forms naturally try to send data and reload the page, which interrupts React's control flow.
import React from 'react'; function MyForm() { function handleSubmit(event) { alert('Form submitted'); } return ( <form onSubmit={handleSubmit}> <input type="text" name="name" /> <button type="submit">Submit</button> </form> ); } export default MyForm;
The Fix
To fix this, call event.preventDefault() inside your handleSubmit function. This stops the page from reloading and lets React handle the form submission smoothly.
import React from 'react'; function MyForm() { function handleSubmit(event) { event.preventDefault(); alert('Form submitted without page reload'); } return ( <form onSubmit={handleSubmit}> <input type="text" name="name" /> <button type="submit">Submit</button> </form> ); } export default MyForm;
Prevention
Always include event.preventDefault() in your onSubmit handlers to stop unwanted page reloads. Use React hooks like useState to manage form inputs and keep your code clean. Enable linting rules that warn about missing preventDefault calls in event handlers.
Related Errors
Common related errors include forgetting to bind the handler in class components (legacy) or trying to access form values without controlled inputs. Always use functional components with hooks and controlled inputs for best results.