A default action is the browser behavior normally triggered by an event. In React, call preventDefault() on the event object when that behavior would interfere with the interface. section 8.4 section 8.11
Preventing a form reload
A button inside a form submits the form by default, which reloads the page and clears input. Handle the form’s submit event instead: const onSubmit = (evt) => { evt.preventDefault(); /* validate and update state */ }; return <form onSubmit={onSubmit}>...</form>. This also handles pressing Enter in an input. section 8.4.1 section 8.4.2
Listing 8.8 Admin form (potentially fixed?)
import { useState } from "react";
function Admin() {
const [password, setPassword] = useState("");
const [isAdmin, setAdmin] = useState(false);
const onSubmit = (evt) => { #1
evt.preventDefault(); #2
if (password === "platypus") {
setAdmin(true);
}
};
return isAdmin ? (
<h1>Bacon is delicious!</h1>
) : (
<form onSubmit={onSubmit}> #3
<input
type="password"
onChange={(evt) => setPassword(evt.target.value)}
/>
<button>Login</button>
</form>
);
}
function App() {
return <Admin />;
}
export default App;
Use the fixed admin form to compare form-level submission handling with the broken button-level click handler. section 8.4.2
Other browser default actions can also be canceled:
- Clicking a link follows its href; preventDefault() stops navigation. section 8.4.3
- Cancellable keyboard events can prevent character insertion or browser commands. section 8.4.3
- Check event.cancellable before relying on preventDefault(); input events cannot be canceled after the input occurs. section 8.4.3

