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.
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();
};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>
);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}`);
};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.