Ojasa Mirai

Ojasa Mirai

ReactJS

Loading...

Learning Level

🟢 Beginner🔵 Advanced
🎪 Event Handling Basics🖱️ Click Events⌨️ Keyboard Events📝 Form Events🎯 Event Handlers with Parameters🚫 Event Default Behavior🔗 Event Delegation⚡ Performance & Events
Reactjs/Events/Event Defaults

🚫 Event Default Behavior — Taking Control of Events

Many HTML elements have default behaviors (forms submit, links navigate). Learn to prevent these defaults and control event propagation.


🎯 preventDefault() — Stop Default Behavior

`preventDefault()` stops the browser from performing its default action for an event. Common uses:

  • Stop form from reloading the page
  • Stop links from navigating
  • Stop context menu from appearing
function FormWithoutReload() {
  const handleSubmit = (e) => {
    e.preventDefault(); // Stop page reload
    console.log("Form submitted without reload!");
  };

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

Without `preventDefault()`, the form would reload the page. With it, your custom code runs instead.

<details>

<summary>📚 More Examples</summary>

// Prevent link navigation
function CustomLink() {
  const handleClick = (e) => {
    e.preventDefault();
    console.log("Link clicked but not navigated");
    // Could navigate programmatically instead
  };

  return (
    <a href="/page" onClick={handleClick}>
      Click me
    </a>
  );
}

// Prevent context menu
function NoContextMenu() {
  const handleContextMenu = (e) => {
    e.preventDefault();
    console.log("Right-click prevented");
  };

  return (
    <div onContextMenu={handleContextMenu}>
      Right-click me - nothing happens!
    </div>
  );
}

</details>

💡 stopPropagation() — Stop Event Bubbling

Events "bubble" up from child to parent elements. `stopPropagation()` stops this bubbling so parent handlers don't fire:

function BubbleExample() {
  const handleDivClick = () => {
    console.log("Div clicked");
  };

  const handleButtonClick = (e) => {
    e.stopPropagation(); // Stop bubbling to div
    console.log("Button clicked");
  };

  return (
    <div onClick={handleDivClick} style={{ padding: "20px", background: "blue" }}>
      <button onClick={handleButtonClick}>Click Button</button>
    </div>
  );
}

When you click the button:

  • Without `stopPropagation()`: Both handlers fire (button AND div)
  • With `stopPropagation()`: Only button handler fires

<details>

<summary>📚 More Examples</summary>

// Modal example: prevent close when clicking inside
function Modal() {
  const [isOpen, setIsOpen] = useState(true);

  const handleBackdropClick = () => {
    setIsOpen(false); // Close modal
  };

  const handleModalContentClick = (e) => {
    e.stopPropagation(); // Don't close when clicking inside
  };

  if (!isOpen) return null;

  return (
    <div
      onClick={handleBackdropClick}
      style={{
        position: "fixed",
        background: "rgba(0,0,0,0.5)",
        width: "100%",
        height: "100%",
      }}
    >
      <div
        onClick={handleModalContentClick}
        style={{
          background: "white",
          padding: "20px",
          margin: "50px auto",
        }}
      >
        <h2>Modal Content</h2>
        <p>Click here - modal stays open</p>
      </div>
    </div>
  );
}

</details>

🎨 Using Both Together

Sometimes you need both:

function FormInModal() {
  const handleFormSubmit = (e) => {
    e.preventDefault(); // Stop form reload
    e.stopPropagation(); // Stop modal from closing
    console.log("Form submitted!");
  };

  return (
    <form onSubmit={handleFormSubmit}>
      <input placeholder="Enter data" />
      <button type="submit">Submit</button>
    </form>
  );
}

🔧 Conditional Prevention

You can conditionally prevent default behavior:

function ConditionalSubmit() {
  const [isValid, setIsValid] = useState(true);

  const handleSubmit = (e) => {
    if (!isValid) {
      e.preventDefault();
      console.log("Form has errors, not submitting");
    } else {
      console.log("Form submitted!");
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        onChange={(e) => setIsValid(e.target.value.length > 0)}
      />
      <button type="submit">Submit</button>
    </form>
  );
}

🎨 Real-World Example: Search with Custom Behavior

function SearchBar() {
  const [query, setQuery] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault(); // Prevent page reload

    if (!query.trim()) {
      console.log("Please enter a search term");
      return;
    }

    console.log("Searching for:", query);
    // Would typically navigate or trigger search API here
    setQuery("");
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        placeholder="Search..."
      />
      <button type="submit">Search</button>
    </form>
  );
}

📊 preventDefault vs stopPropagation

MethodDoesUse When
`preventDefault()`Stops browser's default actionStop form reload, link navigation, etc.
`stopPropagation()`Stops event bubbling to parentsClick on button shouldn't close modal, etc.

🔑 Key Takeaways

  • ✅ Use `e.preventDefault()` to stop default browser behavior
  • ✅ Use `e.stopPropagation()` to prevent bubbling to parent elements
  • ✅ Forms almost always need `preventDefault()`
  • ✅ Modals often need `stopPropagation()` to prevent closing
  • ✅ You can use both methods on the same event
  • ✅ Check validity before preventing default behavior

Ready to practice? Event Delegation | Challenges


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn