Monday, January 6, 2025
Google search engine
HomeLanguagesHow to prevent default behavior in an event callback in ReactJS ?

How to prevent default behavior in an event callback in ReactJS ?

Certain events in Javascript have default actions associated with them. For example, clicking on an anchor tag takes the user to the path specified in the href attribute. A form element can have a submit event that is invoked via a button of type “submit”. This will cause the browser to refresh whenever the button is clicked. While this was necessary in the past in order to allow the backend to process data, most modern web applications do not need a browser to reload every time a form is submitted. 

Often, developers might choose to run their own defined behavior, i.e. prevent the browser from reloading unnecessarily. Let’s find out how to do so.

Creating React Application: Before proceeding to the approach, we have to create a React app.

Step 1: Create a React application using the following command:

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: It will look like the following.

Initial folder Structure 

Step 3: Now that we have the project set up, let us replace the content of App.js, located inside the src folder, with the following code: 

Javascript




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 4: Use the following command to run the app in development mode, and open http://localhost:3000 to view it in the browser:

npm start

We can see clearly that every time the button is clicked, an alert shows up, and when we close the alert, the browser refreshes on its own.

Browser refreshes on its own

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.

Thus, the code for App.js now becomes:

Javascript




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;


This is the new behavior:

No automatic refreshes!

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments