Forms in React – Submitting Data with onSubmit and Action in Search Forms

react-forms-Forms are essential in modern applications. This article walks through building a search form in React using input and button elements. First, we use the onSubmit attribute to manage form submission, then introduce the action attribute to align with native HTML behavior. This structure improves accessibility, readability, and prepares the app for future React updates.submit-search-with-onsubmit-and-action

React formsonSubmitactionpreventDefault

~2 min read • Updated Oct 24, 2025

Introduction


Forms in React behave similarly to HTML, but with enhanced control over state and events. In this article, we build a search form using an input field and a button, then refactor it into a reusable component. Later, we introduce the action attribute to align with native form behavior.


Building a Form with onSubmit


We start by wrapping the input and button inside a form and using onSubmit to handle submission:


<form onSubmit={handleSearchSubmit}>
  <InputWithLabel ... />
  <button type="submit">Submit</button>
</form>

In the handleSearchSubmit function, we use event.preventDefault() to prevent the page from reloading:


const handleSearchSubmit = (event) => {
  setUrl(`${API_ENDPOINT}${searchTerm}`);
  event.preventDefault();
};

Extracting the Form into a Component


We refactor the form into a SearchForm component for better readability and reuse:


const SearchForm = ({ searchTerm, onSearchInput, onSearchSubmit }) => (
  <form onSubmit={onSearchSubmit}>
    <InputWithLabel ... />
    <button type="submit">Submit</button>
  </form>
);

Using Action Instead of onSubmit


In newer versions of React, we can use the action attribute to handle form submission. This attribute receives a function that processes the form data:


const SearchForm = ({ searchTerm, onSearchInput, searchAction }) => (
  <form action={searchAction}>
    <InputWithLabel ... />
    <button type="submit">Submit</button>
  </form>
);

In this case, we no longer need preventDefault():


const searchAction = () => {
  setUrl(`${API_ENDPOINT}${searchTerm}`);
};

Benefits of Using Forms in React


  • Improved structure and readability
  • Keyboard accessibility via Enter key
  • Reusable components for cleaner code
  • Future-proofing with native form behavior via action

Conclusion


Forms in React are a powerful way to collect and submit data. By using onSubmit and later action, we create forms that are both readable and aligned with native HTML behavior. This structure enhances user experience and makes the application easier to maintain and extend.


Written & researched by Dr. Shahin Siami