Categories
React Answers

How to Prevent Form Submission in a React Component?

Spread the love

Sometimes, we want to prevent form submission in a React component.

In this article, we’ll look at how to prevent form submission in a React component.

Prevent Form Submission in a React Component

To prevent form submission in a React component, we should call the event.preventDefault method in our submit event handler function.

For instance, we write:

import React from "react";

export default function App() {
  const onSubmit = (event) => {
    event.preventDefault();
    console.log("submission prevented");
  };

  return (
    <form onSubmit={onSubmit}>
      <input />
      <input type="submit" />
    </form>
  );
}

We have a form with the onSubmit prop set to the onSubmit function so that the onSubmit function is our form’s submit event handler.

In the function, we call event.preventDefault to prevent the default submission behavior.

Therefore, when we click Submit, we see the 'submission prevented' message logged in the console.

Conclusion

To prevent form submission in a React component, we should call the event.preventDefault method in our submit event handler function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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