How To Prevent Form Submission In React

How to Prevent form submission in React

If you don’t know how to prevent form submission in React, don’t worry. We will give you some methods in this article. Read on it.

Event method

We usually understand event as an action acting on an HTML object. We can catch an event and perform specific actions.

When writing a callback function for an event, such as a button click to prevent the browser from handling the click event by default, we usually have methods to handle the event after the callback is processed. Let’s take a look at what they are:

  • Event.createEvent(): Creating a new event must have the initEvent() method called on that event.
  • Event.composedPath(): Returns the event’s route (The objects on which the listener will be called). If the shadow root made with ShadowRoot.mode is closed, nodes in shadow trees are excluded from this.
  • Event.initEvent(): Set a created Event’s value to its initial state. This approach is useless if the event has already been dispatched.
  • Event.preventDefault(): Postpone the event (If it can be canceled).
  • Event.stopImmediatePropagation(): Stop calling any other listeners in this particular instance. Listeners bound to the same element and listeners bound to elements that will be traversed later are included in this.
  • Event.stopPropagation(): Stop passing DOM events.

How to prevent form submission in React

Add onSubmit to form method

Sometimes when you code a form without catching the submit event for it, when you select any button, even if it’s not the submit button in the form, it will also lead to having to submit the whole form. So in this way, we will add the onSubmit event to the form and handle it. Here is an example we can analyze and understand how it works.

Code:

import React from "react";
 
export default function App() {
    const handleSubmit = (event) => {
      	event.preventDefault();
    };
    const handleClick = () => {
      	console.log("You have submitted");
    };
    return (
        <form onSubmit={handleSubmit}>
            <button type="submit" onClick={handleClick}>
              	Submit
            </button>{" "}
        </form>
    )
}

Output:

When we click the button, the console screen will show that you have submitted and have prevented the auto-submit of the program. Or you can see more ways to do it below if this doesn’t work for you.

Use event.preventDefault method

Event.preventDefault

The preventDefault() method of the event object is used to prevent the browser’s default behaviour when an event occurs. Here is a simple example of how it works:

Code:

<a href="https://learnshareit.com/">Homepage</a>
<script type="text/javascript">
    $("a").click(function(event) {
        console.log("You clicked homepage");
        event.preventDefault()
    });
</script>

Output:

In this case, we often get the form submit error when pressing a button other than the submit button in the form. So we can use event.preventDefault() to stop form resubmission and prevent this. Here is a specific example of this problem:

Code:

import React from "react";
 
export default function App() {
    const onSubmit = (event) => {
      	event.preventDefault();
    };

    return (
        <form onSubmit={onSubmit}>
            <input />
            <button>Not Submit</button>
            <input type="submit" value="Submit" />
        </form>
    )
}

As you can see, without preventDefault(), when we press the ‘Not Submit’ button, the form is also submitted, which is annoying for the user. We can prevent the submit event and check if the form is valid or if the correct submit button is selected.

Summary

To summarize, there are many ways to prevent form submission in React. After reading this article, you already know some simple ways, such as adding the onSubmit to form method or using the event.preventDefault() method. Thanks for your reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *