preventDefault()is a method of the Event object in JavaScript.- It is used to prevent the browser's default behavior for a particular event.
- Commonly used in form submissions, anchor tags, right-click menus, drag & drop events, etc.
🔹 Why do we need it?
By default, browsers have built-in behaviors for certain events:
- Clicking on a link (
<a>) → navigates to another page. - Submitting a form → reloads the page.
- Right-clicking → shows context menu.
👉 If we don’t want these default actions, we use event.preventDefault().
🔹 Example 1: Prevent Form Reload
import React, { useState } from "react";
function MyForm() {
const [input, setInput] = useState("");
const handleSubmit = (e) => {
e.preventDefault(); // ❌ stop page refresh
alert("Form submitted: " + input);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Enter something"
/>
<button type="submit">Submit</button>
</form>
);
}
export default MyForm;
✅ Here, preventDefault() stops the form from refreshing the page after submit.
🔹 Example 2: Prevent Anchor Tag Navigation
function MyLink() {
const handleClick = (e) => {
e.preventDefault(); // ❌ stop going to Google
alert("Link clicked, but navigation prevented!");
};
return <a href="https://google.com" onClick={handleClick}>Go to Google</a>;
}
🔹 Difference: preventDefault() vs stopPropagation()
preventDefault()→ Prevents default browser behavior (e.g., form submit, navigation).stopPropagation()→ Stops the event from bubbling up to parent elements.
✅ Summary:preventDefault() is used to stop the browser’s default action for an event, such as preventing form reload or stopping navigation.