Building a Search Form in React with Next.js and useRouter

Over the past few years at Itselftools.com, we have gained extensive experience developing over 30 applications using technologies like Next.js and Firebase. Today, we’re sharing a slice of our expertise by breaking down a React component that effectively utilizes Next.js’s routing capabilities to handle a basic search functionality. This guide will dissect a simple search form, explaining every line of code and how it contributes to the overall functionality.

The Code Snippet:

Here is a React component for a basic search form:

import { useState } from 'react';
import { useRouter } from 'next/router'; export default function SearchForm() { const [query, setQuery] = useState(''); const router = useRouter(); const handleSubmit = (event) => { event.preventDefault(); router.push(`/search?query=${encodeURIComponent(query)}`); }; return ( <form onSubmit={handleSubmit} role='search'> <label htmlFor='search-box'>Search:</label>
 <input id='search-box' type='text' value={query} onChange={(e) => setQuery(e.target.value)} />
 <button type='submit'>Go</button>
 </form>
 );
}
Enter fullscreen mode
Exit fullscreen mode

Breakdown of the Component:

  1. Import Statements: We begin by importing useState from ‘react’ for state management and useRouter from ‘next/router’, which allows us to programmatically navigate.

  2. Function Component: SearchForm is a functional component that utilizes hooks.

  3. State Management: Using useState, we initialize query to an empty string. This state tracks the input from the user.

  4. Form Handling: The handleSubmit function prevents the normal form submission process and uses Next.js’s router to redirect to a search results page, passing the user’s input as a URL query.

  5. Rendering the Form: The form element itself includes an input field where the user types their query, and a submit button. The onChange event on the input updates the state with the current value.

Conclusion:

This simple component elegantly demonstrates using React hooks for state management and Next.js’s useRouter for navigation. If you’re eager to see this code in action, check out some of the applications we’ve built, such as English Adjectives Dictionary, Text to Speech Online, and Rhyming Dictionary. These tools showcase the practical application of the techniques discussed in this guide. Explore these resources and consider how you can integrate similar functionality into your projects.


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

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

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top