Sub topic 6
Preventing default browser behavior
This chapter assumes you can write function components, use JSX, pass props, and call useState. You should also know how to attach an onClick or onChange handler.
What default behavior means
Many DOM elements do something on their own when an event fires. A link navigates to its href. A form submit sends a request and reloads the page. A checkbox toggles. These built-in actions are the browser's default behavior.
In a React app you usually want to handle these actions in JavaScript instead. For example, you may want to validate a form and send the data with fetch, without a page reload. To stop the default action, call e.preventDefault() on the event object that React passes to your handler.
Preventing a form reload
The most common case is a form. Without preventDefault, submitting reloads the page and discards your component state.
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>
);
}The handler is attached to the form's onSubmit, not to the button's onClick. Pressing Enter inside the input also submits the form, and only onSubmit catches both paths.
Preventing link navigation
You can also stop an anchor from navigating, for example when a link triggers an action in your app.
function HelpLink({ onOpenHelp }) {
function handleClick(e) {
e.preventDefault();
onOpenHelp();
}
return (
<a href="/help" onClick={handleClick}>
Help
</a>
);
}Keep the real href. Users can still open the link in a new tab, and assistive technology can still identify it as a link. If the element does not navigate anywhere, a <button type="button"> is often the better choice than a link with no destination.
Common errors
- Returning
false. In plain HTML,onclick="return false"can cancel the default action. In React, returningfalsedoes nothing. Calle.preventDefault()explicitly. - Calling it too late.
preventDefaultmust run while the event is being dispatched. If you call it inside anawaitcontinuation or asetTimeoutcallback, the browser has already performed the default action. Call it first, at the top of the handler, before any asynchronous work. - Calling the handler during render. Writing
onSubmit={handleSubmit()}runs the function while rendering, with no event. Pass the function itself:onSubmit={handleSubmit}. - Attaching to the wrong event. Using
onClickon a submit button misses submissions made with the Enter key. UseonSubmiton the form.
Not every event can be canceled
An event is cancelable only if the browser lets you cancel it. You can check e.cancelable. Most click, submit, and key events are cancelable. Calling preventDefault on a non-cancelable event has no effect.
Be careful with touch and scroll events. Browsers often register wheel and touchstart listeners as passive, which means preventDefault is ignored and the browser may log a warning. If you need to block scrolling, that usually requires a native listener with { passive: false }, covered later in this tutorial.
You can also check whether a handler already canceled an event with e.defaultPrevented. This is useful when a parent component needs to know that a child handled the event.
function Card({ onOpen }) {
function handleClick(e) {
if (e.defaultPrevented) return;
onOpen();
}
return (
<div onClick={handleClick}>
<a href="/docs" onClick={e => e.preventDefault()}>
Docs
</a>
</div>
);
}Here the link's click bubbles to the card, and the card skips onOpen because the link already prevented the default.
Exercise
A form uses <button type="submit" onClick={handleClick}> and has no onSubmit. Inside handleClick you call e.preventDefault(). A user types an email and presses Enter instead of clicking. What happens, and how do you fix it?
Show answer
Pressing Enter submits the form without firing the button's click handler, so the page reloads. The fix is to move the logic to onSubmit on the <form> element and call e.preventDefault() there. That handler runs for both the click and the Enter key.
Exercise
Why does this handler fail to stop the page reload? async function handleSubmit(e) { await validate(); e.preventDefault(); }
Show answer
The await pauses the handler, and the browser performs the default action once the synchronous part of dispatch ends. By the time preventDefault runs, it is too late. Call e.preventDefault() first, then await validate().