liveBook · Manning

Default action

As explained in React Quickly, Second Edition

A default action is the browser behavior normally performed in response to an event when that behavior is not canceled.

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

How React Quickly, Second Edition covers it

How deep it goes
Explains browser defaults, React’s preventDefault() method, form-level handling, Enter-key submission, and cancellable-event limits.
Examples
Uses an admin login form, a button inside a form, link navigation, keyboard input, scrolling, and drag events.
What it assumes
Assumes basic HTML forms and React event handlers while explaining form submission behavior from the browser level.
What you can do after
Apply via React event handlers by moving submission logic to onSubmit and calling preventDefault() when cancellation is required.
How it connects
Connects React event handlers with HTML forms, event objects, event propagation, links, and cancellable events.

Also explained in

Compare how 2 books explain default action →

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.