liveBook · Manning

preventDefault

As explained in React Quickly, Second Edition

preventDefault() is an Event method that cancels an event's default action when the event is cancelable.

preventDefault() cancels an event’s browser default action when the event is cancelable. React event objects provide this method through an API based on HTML events. section 8.4.2 section 8.2.3

For forms, handle the form’s onSubmit event and call evt.preventDefault(). This prevents the browser from submitting to the target URL and reloading the page. section 8.4.2

React form submission

const onSubmit = (evt) => { evt.preventDefault(); if (password === "platypus") setAdmin(true); }; <form onSubmit={onSubmit}> <input type="password" onChange={(evt) => setPassword(evt.target.value)} /> <button>Login</button> </form> Putting the handler on the form handles both clicking Login and pressing Enter in the input. section 8.4.2

The method also cancels other browser actions, such as following a link, scrolling, inserting a typed character, or starting a drag. Check evt.cancellable first when the event type matters; noncancellable events ignore the call. section 8.4.3

How React Quickly, Second Edition covers it

How deep it goes
Explains invocation, form placement, Enter-key behavior, cancellability, and several event examples without descending into event internals.
Examples
Demonstrates an admin login form, link navigation, scrolling, keyboard input, and drag events.
What it assumes
Assumes basic JSX event-handler syntax and event objects while teaching default actions and cancellability through forms.
What you can do after
Apply it via React event handlers to prevent form reloads and other cancellable browser actions.
How it connects
Connects preventDefault() to React event handlers, synthetic events, form submission, link navigation, event bubbling, and stopPropagation().

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Quickly, Second Edition. The section links point to the parts of the book it draws on.