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>
);
}
Breakdown of the Component:
Import Statements: We begin by importing
useState
from 'react' for state management anduseRouter
from 'next/router', which allows us to programmatically navigate.Function Component:
SearchForm
is a functional component that utilizes hooks.State Management: Using
useState
, we initializequery
to an empty string. This state tracks the input from the user.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.Rendering the Form: The form element itself includes an
input
field where the user types their query, and a submit button. TheonChange
event on theinput
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.
Top comments (0)