Sub topic 6
Preventing default browser behavior
This chapter covers what the browser does by default when an event fires, how preventDefault cancels that behavior in React, and where it fails. It assumes you know JavaScript arrow functions, basic JSX, components and props, and the useState hook. You should also have read the earlier chapters on attaching handlers and the event object.
What "default behavior" means
Many DOM events have a built-in browser action attached to them. The browser runs that action after your handlers finish, unless a handler cancels it.
| Element and event | Default action |
|---|---|
| `<form>` submit | Sends a request and reloads the page |
| `<a href>` click | Navigates to the URL |
| `<input type="checkbox">` click | Toggles the checked state |
| `<input>` keydown | Inserts the typed character |
| Any element `contextmenu` | Opens the browser's context menu |
| Scrollable element `wheel` | Scrolls the content |
| Draggable element `dragover` on a drop target | Rejects the drop |
Default behavior is separate from propagation. Propagation decides which handlers run as the event travels through the tree. Default behavior is what the browser does once the dispatch finishes. The two are controlled by different methods, and cancelling one does not cancel the other.
Calling preventDefault
Every React event object has a preventDefault() method. It tells the browser to skip the default action for this event.
function ExternalLink() {
function handleClick(e) {
e.preventDefault();
console.log('Link clicked, but we did not navigate');
}
return (
<a href="https://example.com" onClick={handleClick}>
Example
</a>
);
}Without the e.preventDefault() call, the console message would appear and the browser would then navigate away. With it, the click is handled and nothing else happens.
React's event object is a SyntheticEvent. It wraps the native event and forwards preventDefault() to it, so the call has the same effect as in plain JavaScript. You can read e.defaultPrevented afterwards to check whether any handler has cancelled the event.
function Link({ href, children }) {
function handleClick(e) {
console.log('before:', e.defaultPrevented);
e.preventDefault();
console.log('after:', e.defaultPrevented);
}
return (
<a href={href} onClick={handleClick}>
{children}
</a>
);
}This logs before: false and then after: true.
Preventing form submission
The most common use is a form. A <form> with no action attribute submits to the current URL and reloads the page, which destroys all component state. In a React app you almost always handle the submission yourself.
import { useState } from 'react';
function SignupForm({ onSubmit }) {
const [email, setEmail] = useState('');
function handleSubmit(e) {
e.preventDefault();
onSubmit(email);
}
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={e => setEmail(e.target.value)}
/>
<button type="submit">Sign up</button>
</form>
);
}Attach the handler to the form's onSubmit, not to the button's onClick. A form can be submitted by pressing Enter inside a text field, and that path never fires a click on the button. Handling onSubmit covers every route.
The next chapters cover form submission in more detail. Here the point is the order of operations: the browser fires submit, your handler runs, and only then would the browser reload. Calling preventDefault() anywhere in the handler cancels the reload.
The throw-before-prevent trap
If your handler throws before it reaches preventDefault(), the default action still happens. The page reloads and the error disappears from the console.
function BrokenForm({ user }) {
function handleSubmit(e) {
// Throws if user is undefined, so preventDefault never runs
console.log(user.name);
e.preventDefault();
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Save</button>
</form>
);
}If user is undefined, the first line throws a TypeError. The page then reloads, and the error may flash by or be lost. Calling e.preventDefault() first keeps the page alive so you can read the error.
Preventing default on keyboard events
Keyboard events let you filter what the user can type. Here the input accepts only digits by cancelling the default action of other keys.
function DigitsOnlyInput() {
function handleKeyDown(e) {
const isDigit = /^[0-9]$/.test(e.key);
const isControl = e.key.length > 1 || e.ctrlKey || e.metaKey;
if (!isDigit && !isControl) {
e.preventDefault();
}
}
return <input type="text" onKeyDown={handleKeyDown} />;
}Keys such as Backspace, ArrowLeft, and Tab have names longer than one character, so the isControl check lets them through. Without it, the user could not delete text or move focus. Shortcuts like Ctrl+V also pass through.
This approach is fragile. It does not stop pasted text, drag-and-drop text, or mobile keyboards that report unusual key values. Treat it as a convenience, and validate the final value in the onChange handler or on the server.
The data flow of a cancelled event
The diagram shows where preventDefault sits in the lifecycle of a click on a link.
Conditional prevention
You do not have to cancel every time. A common pattern is to cancel only when your own code can handle the action. A client-side router link is a typical case. It lets the browser handle modified clicks, such as Ctrl+click to open a new tab, and handles plain clicks itself.
function RouterLink({ to, navigate, children }) {
function handleClick(e) {
const isModified = e.metaKey || e.ctrlKey || e.shiftKey || e.altKey;
const isPrimaryButton = e.button === 0;
if (isPrimaryButton && !isModified) {
e.preventDefault();
navigate(to);
}
}
return (
<a href={to} onClick={handleClick}>
{children}
</a>
);
}Keeping the real href matters. Search engines, screen readers, and the "open in new tab" menu all rely on it. Cancelling the click while keeping the href gives you both client-side navigation and normal link behavior.
Common errors
Returning false does nothing
In plain HTML, an inline onclick="return false" cancels the default action. In React, returning false from a handler has no effect. You must call preventDefault().
function Wrong() {
// This does NOT stop the navigation
return <a href="/next" onClick={() => false}>Next</a>;
}
function Right() {
return (
<a href="/next" onClick={e => e.preventDefault()}>
Next
</a>
);
}Calling preventDefault after an await
Cancellation must happen while the event is still being dispatched. Once the handler has yielded to the event loop, the browser has already run the default action.
function AsyncForm() {
async function handleSubmit(e) {
await validate(); // too late: the handler has already returned
e.preventDefault(); // has no effect on the submit
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Save</button>
</form>
);
}
async function validate() {
return true;
}An async function runs synchronously until its first await. After the await, the rest runs later, and by then the page has already started to reload. Call preventDefault() before the first await, then do the asynchronous work.
function AsyncFormFixed() {
async function handleSubmit(e) {
e.preventDefault();
await validate();
// submit with fetch here
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Save</button>
</form>
);
}
async function validate() {
return true;
}Events that cannot be cancelled
Some events are not cancelable. For these, preventDefault() does nothing. You can check e.cancelable before relying on it. Scroll events are the usual example: by the time scroll fires, the scroll has already happened.
Passive wheel and touch listeners
Browsers treat some touch and wheel listeners as passive, meaning the listener promises not to call preventDefault(). A passive listener that calls it gets a console warning and the call is ignored. React attaches its onWheel, onTouchStart, and onTouchMove handlers as passive listeners at the root, so e.preventDefault() in those props is ignored in current browsers. If you need to cancel a wheel or touch gesture, register a native listener with { passive: false } in an effect. A later chapter covers that technique.
Often CSS is the better tool. The touch-action and overscroll-behavior properties control gesture behavior without any JavaScript.
Confusing preventDefault with stopPropagation
| Method | What it stops | What it leaves alone |
|---|---|---|
| `preventDefault()` | The browser's built-in action | Other handlers still run, and the event still bubbles |
| `stopPropagation()` | The event reaching handlers on ancestor elements | The browser's built-in action still happens |
A link whose click handler calls only stopPropagation() still navigates. A form whose submit handler calls only stopPropagation() still reloads. Call both when you need both effects.
Buttons inside forms
A <button> inside a <form> defaults to type="submit". A click on it submits the form even if the button is meant for something else, such as adding a row.
function Toolbar() {
return (
<form onSubmit={e => e.preventDefault()}>
<button type="button" onClick={() => console.log('add row')}>
Add row
</button>
<button type="submit">Save</button>
</form>
);
}Setting type="button" removes the default submit action at the source. This is cleaner than calling preventDefault() in the button's click handler, because the markup states the button's role.
Choosing the right approach
- Use
preventDefault()when the browser has a default action that your code replaces, such as form submission or link navigation. - Use the right
typeattribute when the element should not trigger the action at all, such astype="button". - Use CSS when the goal is to control scrolling, touch gestures, or text selection.
- Use a native listener with
{ passive: false }when you need to cancelwheelortouchmoveevents. - Always validate on the server. Cancelling key presses or submissions in the browser is a user-interface aid and not a security control.
Exercise
A form's submit handler is async function handleSubmit(e) { const ok = await checkEmail(email); if (!ok) return; e.preventDefault(); save(); }. The page still reloads on every submit. What is wrong, and how do you fix it?
Show answer
preventDefault() runs after an await, and in the !ok branch it is never reached at all. The browser decides whether to run the default action when the synchronous part of the handler ends, which is at the first await. By the time preventDefault() would run, the reload has already started. Move e.preventDefault() to the first line of the handler, before the await. Then do the async check and call save() when it passes.
Exercise
You write <a href="/docs" onClick={e => { e.stopPropagation(); openDocsPanel(); }}>Docs</a> and the browser still navigates to /docs after the panel opens. Why, and what is the smallest change that makes the link open only the panel?
Show answer
stopPropagation() only stops the event from reaching ancestor handlers. It does not cancel the browser's navigation. Replace it with e.preventDefault(), or add e.preventDefault() as well if you also need to keep ancestors from seeing the click.
Exercise
In your own words, why is onSubmit on the form a better place to call preventDefault() than onClick on the submit button?
Show answer
A form can be submitted without clicking the button, for example by pressing Enter in a text field. That path does not fire the button's click handler, so the page would reload. The submit event fires for every route, so cancelling it there covers all of them.