Sometimes, when you click a link or submit a form, the browser does something automatically. Preventing default behavior stops that automatic action so you can control what happens next.
Preventing default behavior in React
function handleEvent(event) { event.preventDefault(); // your code here }
The event object is passed automatically to event handlers in React.
Calling event.preventDefault() stops the browser's default action for that event.
function handleClick(event) { event.preventDefault(); alert('Link clicked but no page change!'); }
function handleSubmit(event) { event.preventDefault(); console.log('Form submitted without page reload'); }
This React component shows a link and a form. Clicking the link or submitting the form will not trigger the browser's default actions. Instead, alerts appear to confirm the events were caught and handled.
Accessibility is considered by adding an aria-label to the link. The layout uses semantic HTML and spacing for clarity.
import React from 'react'; export default function PreventDefaultExample() { function handleLinkClick(event) { event.preventDefault(); alert('You clicked the link, but no page change!'); } function handleFormSubmit(event) { event.preventDefault(); alert('Form submitted without reload!'); } return ( <main> <h1>Prevent Default Behavior Example</h1> <a href="https://example.com" onClick={handleLinkClick} aria-label="Example link">Example Link</a> <form onSubmit={handleFormSubmit} style={{ marginTop: '1rem' }}> <button type="submit">Submit Form</button> </form> </main> ); }
Always pass the event object to your handler to use preventDefault().
Preventing default behavior is useful to create custom interactions without page reloads or navigation.
Use event.preventDefault() to stop the browser's automatic action.
This lets you control what happens when users click links or submit forms.
It helps create smoother, interactive web apps without page reloads.