Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
How to bind an event handler in JSX callback ?
Next article icon

How to Prevent Default Behavior in an Event Callback in React JS ?

Last Updated : 12 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

React JS provides events to create interactive and responsive user interfaces. One characteristic of event handling is to prevent the default behavior of events in certain cases. This article covers the process of preventing default behavior in event callbacks within React JS.

Prerequisites:

  • Basic JavaScript and ES6 concepts
  • Knowledge of React JS
  • Event Handling

Approach

To prevent default behaviour in event callback in react we will be using the preventDefault method. It is used to prevent the browser from executing any default action.

Steps to Create React Application

Step 1: Initialize the react app using this command in the terminal.

npx create-react-app myapp

Step 2: After creating your project folder, i.e. myapp, move to it using the following command:

cd myapp

Project Structure:

Initial folder Structure 

The updated dependencies in package.json file will look like:

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

Step 3: Create a basic input form to take the name input without using preventDefault funtion.

JavaScript
// Filename - App.js  import React, { useState } from "react";  function App() {     const [name, setName] = useState("");      const handleSubmit = () => {         alert("There will be a browser reload once the alert box is closed.");     };      return (         <form onSubmit={handleSubmit}>             <input                 type="text"                 value={name}                 placeholder="Name"                 onChange={(e) => setName(e.target.value)}             />             <button type="submit">Click</button>         </form>     ); }  export default App; 

We have a form element with a submit event, wrapping a button. When the button is clicked, the handleSubmit function is triggered.

Step to run the application: Use the following command to run the app and open http://localhost:3000

npm start

Output:

Preventing default behaviour

We can prevent this default behavior by making a small modification to the definition of the handleSubmit function. We call a preventDefault on the event when submitting the form, and this will cancel the default event behavior (browser refresh) while allowing us to execute any code we write inside handleSubmit.

Example: This example uses preventDefault method to prevent browsers default actions on the input field and input form.

JavaScript
// Filename - App.js  import React, { useState } from "react";  function App() {     const [name, setName] = useState("");      const handleSubmit = (event) => {         event.preventDefault();         alert("The browser will not reload when the alert box is closed.");     };      return (         <form onSubmit={handleSubmit}>             <input                 type="text"                 value={name}                 placeholder="Name"                 onChange={(e) => setName(e.target.value)}             />             <button type="submit">Click</button>         </form>     ); }  export default App; 

Output: This is the new behavior

Conclusion

The preventDefault method is used to prevent the default browser actions hence we can use it to prevern the default action in event callbacks.



Next Article
How to bind an event handler in JSX callback ?

S

swap24
Improve
Article Tags :
  • Geeks Premier League
  • ReactJS
  • Web Technologies
  • Geeks-Premier-League-2022
  • React-Questions
  • Web technologies

Similar Reads

  • How to prevent the default action of an event in JavaScript ?
    The term "default action" usually refers to the default behavior or action that occurs when an event is triggered. Sometimes, it becomes necessary to prevent a default action of an event. Let's create HTML structure with event and function that needs to prevent the default actions. [GFGTABS] HTML
    3 min read
  • How to bind an event handler in JSX callback ?
    ReactJS is a JavaScript library focused on building user interfaces. JSX callbacks in React are used to associate event handlers with elements in JSX code. Event handlers, like those for button clicks or form submissions, are functions triggered by events. In React, event handlers are bound to eleme
    3 min read
  • How to create an event in React ?
    In the development of contemporary webpages, user interactions play a pivotal role. These interactions include mouse clicks, keypresses, or even uncommon events like connecting a battery to a charger. As developers, our task is to actively "listen" to these events and subsequently ensure that our ap
    2 min read
  • How to create Popup box in React JS ?
    Popup boxes, also known as modal or dialog boxes, are common UI elements used to display additional content or interactions on top of the main page. Creating a popup box in React can be achieved using various approaches, including libraries or custom implementations. We will use the Reactjs-popup li
    2 min read
  • How to Conditionally Disable a Form Input in React-Bootstrap ?
    In this article, we will see how to conditionally disable a form input in React-Bootstrap. React-Bootstrap is a popular open-source library for building frontend components with the advantage of the pre-build component features of Bootstrap. Creating React Application And Installing ModuleStep 1: Cr
    3 min read
  • How to avoid binding by using arrow functions in callbacks in ReactJS?
    In React class-based components when we use event handler callbacks, it is very important to give special attention to the 'this' keyword. In these cases the context this is undefined when the callback function actually gets invoked that's why we have to bind the context of this. Now if binding all
    2 min read
  • How to Disable a Button in React JS ?
    Disabling a button in React JS means making it unclickable and visually indicating its unavailability. This is done by setting the button's disabled attribute to true. It's used for controlled interactions, like form submissions with valid data. A disabled button becomes unclickable and visually sig
    4 min read
  • How to pass a parameter to an event handler or callback ?
    In React, to pass a parameter to an event handler or callback simply means to execute that function or code when the event is triggered. It links the events to the respective functions. Prerequisites:React JSEvent HandlersReact JS Class ComponentApproachWe will define a function to create a window a
    2 min read
  • How to Reset a File Input in React.js ?
    To reset a file input in React JS, we can use the useRef Hook to create a reference to the input element and modify its properties using the DOM API. Prerequisites:NPM & Node JSReact JSReact useRef HookApproach:To reset a file input in react we will create a reset button and handleReset function
    2 min read
  • How to get key attribute of parent div when button is clicked in ReactJS ?
    In ReactJS, it's a common practice to render multiple dynamically generated components within a parent container. Each child component often comes with its unique set of attributes, including a distinctive key attribute that aids React in optimizing updates and re-renders. Prerequisites:NodeJS or NP
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences