What is event.preventDefault() – What It Does

In JavaScript (and React), when you submit a form, the browser by default:

  • Reloads the page (sends a GET or POST request)
  • Clears everything unless otherwise handled

That’s the default behavior of an HTML form.

🛑 preventDefault() stops that from happening.

It tells the browser:

“❌ Don’t reload the page or do the default thing — I’ll handle everything with JavaScript.”

✅ Example Without preventDefault()

function FormExample() {
  const handleSubmit = (e) => {
    console.log("Form submitted");
  };

  return (
    <form onSubmit={handleSubmit}>
      <button type="submit">Submit</button>
    </form>
  );
}

🟥 Problem:
The form submits → page reloads → console log disappears → you lose state.

✅ Example With preventDefault()

function FormExample() {
  const handleSubmit = (e) => {
    e.preventDefault();
    console.log("Form submitted ✅");
  };

  return (
    <form onSubmit={handleSubmit}>
      <button type="submit">Submit</button>
    </form>
  );
}

✅ Now:

  • No page reload
  • Console log stays
  • React controls everything

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *