How to Prevent Default Behavior in React Events
event.preventDefault() inside your event handler function. This stops actions like form submission or link navigation from happening automatically.Why This Happens
By default, some HTML elements like forms and links perform actions automatically when interacted with. For example, submitting a form reloads the page. React event handlers receive an event object, but if you don't stop the default behavior, the browser will still do its usual action.
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 stop the page from reloading, call event.preventDefault() inside the event handler. This tells the browser not to perform its default action, so you can control what happens next.
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 React event handlers when you want to stop the browser's default behavior. This is common with forms, links, and drag-and-drop events. Use linting tools like ESLint with React plugin to warn if you forget to prevent defaults where needed.
Also, name your event parameter clearly (like event or e) and call preventDefault() early in the handler to avoid unexpected behavior.
Related Errors
Sometimes developers forget to pass the event object to the handler or try to call preventDefault() outside the event context, causing errors like Cannot read property 'preventDefault' of undefined. Always ensure your handler receives the event parameter.
Also, using href="#" on links without preventing default can cause unwanted page jumps. Use event.preventDefault() or better semantic elements.