Preventing Default Browser Behaviour in React JS
1. Introduction
Preventing Default Browser Behaviour is an important concept in React JS event handling. Web browsers automatically perform certain actions when users interact with elements such as forms, links, buttons, and input fields. Sometimes these default actions are not suitable for our application, so we need to stop them and execute our own JavaScript or React logic.
In React, we commonly prevent a browser's default action by calling event.preventDefault() inside an event handler.
Example: When a user submits a form, the browser may reload the page. In a React application, we often want to handle the submitted data without refreshing the entire page. We can prevent the default form submission and process the data using React.
2. What Is Default Browser Behaviour?
Default browser behaviour refers to an action the browser performs automatically when a user interacts with a particular HTML element. These actions are built into the browser and do not always require custom JavaScript code.
| HTML Element |
Default Behaviour |
Possible Reason to Prevent It |
<form> |
Submits the form and may reload or navigate the page. |
Handle form data using React without a full-page refresh. |
<a> |
Navigates to the URL specified in its href. |
Run custom logic or handle navigation in a single-page application. |
<input type="submit"> |
Submits its associated form. |
Validate data or process it before submission. |
<input type="checkbox"> |
Changes its checked state when activated. |
Occasionally control or replace a particular interaction. |
| Right-click on a webpage |
Usually opens the browser context menu. |
Implement a custom context menu when genuinely required. |
Important: Not every default action should be prevented. Browser behaviours such as opening links, keyboard navigation, and form controls are useful for accessibility and usability. Prevent them only when your application has a clear alternative.
3. What Is event.preventDefault()?
event.preventDefault() is a method that prevents the browser from carrying out the default action associated with an event, provided that the event is cancelable and the method is called at an appropriate time.
React event handlers receive an event object, commonly called event or e. You can call preventDefault() on that event object.
Syntax
function handleEvent(event) {
event.preventDefault();
// Write your custom logic here
}
Using an Arrow Function
const handleEvent = (event) => {
event.preventDefault();
console.log("Default browser action prevented");
};
Understanding the Syntax
event: The event object provided to the event handler.
preventDefault(): Requests that the browser skip the event's default action.
console.log(): Demonstrates that custom code can run after preventing the default action.
4. Why Is Preventing Default Behaviour Used in React?
React applications frequently update the interface without reloading the entire webpage. Preventing default behaviour can help the application handle interactions in a controlled way.
- Prevent unnecessary page reloads: Handle form submissions inside React.
- Control form processing: Validate user input before sending data to a server.
- Handle custom navigation: Intercept a link click when the application needs to perform a different action.
- Improve user experience: Display validation messages or success notifications without losing the current interface state.
- Run custom event logic: Replace a browser action with a deliberate application-specific interaction.
5. Preventing Default Behaviour in a Form
One of the most common uses of event.preventDefault() in React is handling form submission. Without custom handling, a traditional HTML form submission can navigate to another page or cause a full-page reload.
Example: Preventing Form Submission Reload
import React from "react";
function LoginForm() {
const handleSubmit = (event) => {
event.preventDefault();
alert("Form submitted without a page reload!");
};
return (
<form onSubmit={handleSubmit}>
<label htmlFor="username">Username:</label>
<input id="username" type="text" required />
<button type="submit">Submit</button>
</form>
);
}
export default LoginForm;
Explanation
- The user enters a username.
- The user clicks the Submit button or submits the form using the keyboard.
- The form triggers its
onSubmit handler.
- The handler receives the event object.
event.preventDefault() prevents the browser's normal form submission.
- The alert runs, and the page does not reload as a result of the default form submission.
Key point: Put submission logic on the form's onSubmit handler rather than relying only on the button's onClick. This also supports keyboard-based form submission.
6. Handling Form Data Without Reloading the Page
In a React application, you can prevent the default form action and then read or manage the submitted values. The following example uses controlled inputs with React state.
import { useState } from "react";
function ContactForm() {
const [name, setName] = useState("");
const [message, setMessage] = useState("");
const [submitted, setSubmitted] = useState(false);
const handleSubmit = (event) => {
event.preventDefault();
setSubmitted(true);
console.log({ name, message });
};
return (
<form onSubmit={handleSubmit}>
<label htmlFor="name">Name:</label>
<input
id="name"
value={name}
onChange={(event) => setName(event.target.value)}
required
/>
<label htmlFor="message">Message:</label>
<textarea
id="message"
value={message}
onChange={(event) => setMessage(event.target.value)}
required
/>
<button type="submit">Send Message</button>
{submitted && <p>Your message has been received.</p>}
</form>
);
}
export default ContactForm;
How it works: The onChange handlers update state as the user types. When the form is submitted, preventDefault() stops the normal browser submission, and React displays the confirmation message without a full-page refresh.
Note: This example demonstrates client-side handling only. In a real application, you would usually send the data to a backend API and handle loading, success, and error states.
7. Preventing Default Behaviour in Anchor Links
An anchor element uses the href attribute to navigate to another page or location. Sometimes, an application needs to intercept a click and execute custom logic instead of following the link.
Example: Preventing Link Navigation
function CustomLink() {
const handleClick = (event) => {
event.preventDefault();
alert("Navigation was prevented!");
};
return (
<a href="https://example.com" onClick={handleClick}>
Click Here
</a>
);
}
export default CustomLink;
Explanation: When the user clicks the link, the click handler runs. Calling event.preventDefault() prevents the browser from navigating to the URL. The alert is displayed instead.
Important: Do not prevent link navigation unnecessarily. If you are building a React single-page application, use your routing library's navigation features when appropriate. Keep links usable with keyboard navigation and standard browser controls.
8. Preventing Default Behaviour with Custom Validation
Sometimes, a form should be processed only when its values meet certain conditions. You can prevent the default submission, validate the input, and display a message when the data is invalid.
import { useState } from "react";
function EmailForm() {
const [email, setEmail] = useState("");
const [message, setMessage] = useState("");
const handleSubmit = (event) => {
event.preventDefault();
if (!email.includes("@")) {
setMessage("Please enter a valid email address.");
return;
}
setMessage("Email accepted successfully!");
};
return (
<form onSubmit={handleSubmit}>
<label htmlFor="email">Email Address:</label>
<input
id="email"
type="text"
value={email}
onChange={(event) => setEmail(event.target.value)}
/>
<button type="submit">Continue</button>
{message && <p>{message}</p>}
</form>
);
}
export default EmailForm;
Explanation:
- The user enters an email address.
- The form's
onSubmit handler runs.
- The browser's default form submission is prevented.
- The code checks whether the input contains an
@ symbol.
- React displays an error or success message without reloading the page.
Note: This is a simple demonstration, not complete email validation. In real projects, use appropriate input validation and validate data again on the server. Native HTML validation, such as type="email" and required, may also be useful.
9. Preventing Default Behaviour in Drag-and-Drop Events
Drag-and-drop interfaces sometimes need event.preventDefault() inside the onDragOver handler to allow an element to act as a drop target.
function DropZone() {
const handleDragOver = (event) => {
event.preventDefault();
};
const handleDrop = (event) => {
event.preventDefault();
alert("Item dropped successfully!");
};
return (
<div
onDragOver={handleDragOver}
onDrop={handleDrop}
style={{
border: "2px dashed gray",
padding: "30px",
textAlign: "center"
}}
>
Drag and drop an item here
</div>
);
}
export default DropZone;
Explanation: The onDragOver handler prevents the browser's default handling of the drag-over event, which is necessary for a normal drop operation on this target. The onDrop handler prevents any applicable default drop action and runs custom logic.
10. Difference Between preventDefault() and stopPropagation()
These two methods are often confused, but they perform different tasks in React event handling.
| Feature |
preventDefault() |
stopPropagation() |
| Purpose |
Prevents an event's default browser action. |
Stops the event from propagating to ancestor event handlers. |
| Effect on form submission |
Can prevent normal form submission. |
Does not by itself prevent form submission. |
| Effect on link navigation |
Can prevent navigation caused by the link click. |
Does not by itself prevent navigation. |
| Effect on parent handlers |
Does not stop event propagation. |
Stops further propagation through the event path. |
| Typical use |
Custom form handling or suppressing a browser default action. |
Preventing a child interaction from triggering a parent handler. |
Example of Both Methods
function EventExample() {
const handleParentClick = () => {
console.log("Parent clicked");
};
const handleChildClick = (event) => {
event.preventDefault();
event.stopPropagation();
console.log("Child clicked");
};
return (
<div onClick={handleParentClick}>
<a href="https://example.com" onClick={handleChildClick}>
Click the link
</a>
</div>
);
}
export default EventExample;
When the link is clicked, its navigation is prevented and its click event does not propagate to the parent handler. The child handler still runs.
11. Common Mistakes When Using preventDefault()
- Forgetting to call the method: Writing
event.preventDefault without parentheses does not call the method.
- Using the wrong event handler: To handle form submission reliably, use
onSubmit on the form.
- Expecting it to stop propagation:
preventDefault() does not stop parent event handlers from running.
- Calling it too late: Prevent the default action within the appropriate event handler before the browser performs that action.
- Blocking every link: Preventing all navigation can make an application confusing and inaccessible.
- Ignoring form validation: Preventing a page reload does not automatically validate data or make it safe.
- Assuming every event is cancelable: Calling the method has no effect on a non-cancelable event.
- Confusing it with React state: The method controls a browser default action; it does not automatically update component state.
12. Best Practices
- Use
event.preventDefault() only when you need to override a default browser action.
- Place form submission logic in the form's
onSubmit handler.
- Use controlled inputs and React state when the interface needs to respond to user input.
- Use native HTML validation where appropriate, and perform server-side validation for submitted data.
- Use semantic elements such as
<button> and <a> instead of clickable generic containers whenever possible.
- Keep keyboard access and accessibility in mind when changing normal browser interactions.
- Use
stopPropagation() only when you specifically need to control event propagation.
- For asynchronous requests, handle loading states, errors, and successful responses rather than assuming the request succeeded.
13. Mini Project: React Feedback Form
Objective: Build a feedback form that prevents the default browser submission, checks the input, and displays a confirmation message.
Complete Example
import { useState } from "react";
function FeedbackForm() {
const [name, setName] = useState("");
const [feedback, setFeedback] = useState("");
const [status, setStatus] = useState("");
const handleSubmit = (event) => {
event.preventDefault();
if (!name.trim() || !feedback.trim()) {
setStatus("Please fill in all fields.");
return;
}
setStatus(`Thank you, ${name.trim()}, for your feedback!`);
setName("");
setFeedback("");
};
return (
<div>
<h2>Feedback Form</h2>
<form onSubmit={handleSubmit}>
<label htmlFor="feedback-name">Your Name:</label>
<input
id="feedback-name"
value={name}
onChange={(event) => setName(event.target.value)}
required
/>
<label htmlFor="feedback-message">Your Feedback:</label>
<textarea
id="feedback-message"
value={feedback}
onChange={(event) => setFeedback(event.target.value)}
required
/>
<button type="submit">Submit Feedback</button>
</form>
{status && <p role="status">{status}</p>}
</div>
);
}
export default FeedbackForm;
Project Explanation
useState() stores the name, feedback, and status message.
- The input and textarea update state through their
onChange handlers.
- The form triggers
handleSubmit when submitted.
event.preventDefault() prevents the browser's normal form submission.
- The code checks whether the name and feedback contain meaningful text.
- React displays a confirmation or validation message without a full-page reload.
- The form fields are cleared after valid feedback is accepted.
This example does not send feedback to a server. A production version should submit the data to an API and show an appropriate message based on the actual response.
14. Interview Questions and Answers
Q1. What is default browser behaviour?
It is the action a browser automatically performs in response to an interaction, such as submitting a form or navigating through a link.
Q2. What is event.preventDefault() in React?
It is a method used inside an event handler to prevent the browser from performing the event's default action when that action can be canceled.
Q3. Why do React forms commonly use preventDefault()?
It allows the application to process form data using JavaScript and React without the browser performing its normal form submission and page reload.
Q4. Does preventDefault() stop event bubbling?
No. It prevents the default browser action. To stop an event from propagating to ancestor handlers, use event.stopPropagation().
Q5. Can preventDefault() be used on anchor links?
Yes. It can prevent the default navigation caused by a link click, allowing custom logic to run instead.
Q6. Does preventDefault() validate form data?
No. It only prevents the default action. Validation must be implemented separately using HTML validation, JavaScript logic, or appropriate server-side checks.
Q7. What happens if preventDefault() is not called on a normally submitted form?
The browser may submit the form to its configured destination and navigate or reload the page according to the form's attributes.
Q8. Can preventDefault() be used on every event?
No. It only affects cancelable default actions. Calling it on a non-cancelable event has no effect.
Q9. Where should preventDefault() be written in a React form?
Usually inside the function assigned to the form's onSubmit handler.
Q10. Does preventDefault() update React state?
No. It does not update state automatically. Use a state setter, such as setMessage(), to update the component's state.
15. Practice Exercises
- Create a login form that displays the entered username without reloading the page.
- Create a registration form that checks whether required fields are filled in before displaying a confirmation message.
- Create a link that displays an alert instead of navigating to another website.
- Build a feedback form that prevents default submission and shows a status message.
- Create a parent and child click example to demonstrate the difference between
preventDefault() and stopPropagation().
- Create a drag-and-drop area and use
preventDefault() in the appropriate drag event handlers.
16. Quick Revision Checklist
- Understand default browser behaviour.
- Know the purpose and syntax of
event.preventDefault().
- Use
onSubmit for React form submission handling.
- Understand how to handle form data without a page reload.
- Know how to prevent default link navigation when necessary.
- Distinguish
preventDefault() from stopPropagation().
- Remember that preventing default behaviour does not replace validation or server communication.
- Use semantic HTML and preserve accessibility.
17. Conclusion
Preventing Default Browser Behaviour is a fundamental React event-handling technique. By using event.preventDefault(), developers can control actions such as form submission, link navigation, and drag-and-drop handling when the default behaviour is not appropriate. Combined with React state, form validation, and event handlers, it helps build responsive user interfaces without unnecessary full-page reloads.
18. Useful Learning Resources