If you are frequently using React for front-end development, you might end up having to use JavaScript for a lof of your forms. However, in some cases, a HTML form might be enough! Let’s take a look at a very basic search form.
Creating the form
First, let’s create our SearchForm
component. We only need four lines of code:
SearchForm.tsx
<form role="search" action="/search">
<input aria-label="Search articles" type="search" name="q" required />
<input type="submit" value="Search" />
</form>
That’s it! Nothing more. To understand how this works, let’s take a look at what happens when we submit a HTML form. If you've ever made a form in React, you probably had to add event.preventDefault()
to prevent the page from reloading on form submit. That’s because when we submit a HTML form, the following happens:
- We get redirected to the URL specified in the form’s
action
attribute - The form values get appended to this URL, in the format
?fieldName=fieldValue
So if we enter “pizza” in the search input, submitting the form will take us to the following URL: /search?q=pizza
. If the form doesn’t have an action
specified, we get redirected to the current page, which is the behaviour we usually avoid with event.preventDefault()
.
Getting the query from the route params
Now that we’ve been redirected to the search page, we just need to grab the query from the URL. How you achieve this will depend on the routing system you’re using, but it will look something like this:
let [searchParams] = useSearchParams();
const query = searchParams.get("q");
const router = useRouter();
const { q: query } = router.query;
Demo
We don’t even need to press the “Search” button to submit the form, as HTML forms can also be submitted with the Enter key!
export default function Home() { return ( <form role="search" action="/search"> <input aria-label="Search articles" type="search" name="q" required /> <input type="submit" value="Search" /> </form> ); }