Prevent default

2 snippets in React

REReact

Form Submission

RE · Forms
syntax
// Traditional
<form onSubmit={handleSubmit}>
// React 19 Actions
<form action={actionFn}>
example
// Traditional approach
function FeedbackForm() {
  const [message, setMessage] = useState('');
  const [submitted, setSubmitted] = useState(false);

  async function handleSubmit(e) {
    e.preventDefault();
    await sendFeedback(message);
    setSubmitted(true);
    setMessage('');
  }

  if (submitted) return <p>Thank you for your feedback!</p>;

  return (
    <form onSubmit={handleSubmit}>
      <textarea
        value={message}
        onChange={e => setMessage(e.target.value)}
        required
      />
      <button type="submit">Submit</button>
    </form>
  );
}

Note With onSubmit, always call e.preventDefault() to stop the browser from reloading the page. With React 19 form actions, preventDefault is handled automatically. Both patterns are valid -- actions are newer and reduce boilerplate.

Preventing Default & Propagation

RE · Event Handling
syntax
e.preventDefault();    // stop default browser action
e.stopPropagation();   // stop bubbling to parent handlers
example
function DropZone({ onFileDrop }) {
  function handleDragOver(e) {
    e.preventDefault(); // Required to allow drop
  }

  function handleDrop(e) {
    e.preventDefault();
    e.stopPropagation();
    const files = Array.from(e.dataTransfer.files);
    onFileDrop(files);
  }

  return (
    <div
      onDragOver={handleDragOver}
      onDrop={handleDrop}
      className="drop-zone"
    >
      Drop files here
    </div>
  );
}

Note Use preventDefault for links, form submissions, and drag-and-drop. Use stopPropagation sparingly -- it makes debugging harder. Prefer checking the event target to decide whether to act instead of stopping propagation.