Course Content
Next.js 14
Next.js 14
Search Functionality
Theory
Before implementing search functionality, it is essential to understand these client hooks.
useSearchParams
;- Allows access to current URL parameters;
- Example: For the URL
/dashboard/invoices?page=1&query=pending
, it provides{page: '1', query: 'pending'}
.
usePathname
;- Reads the current URL's pathname;
- Example: For the route
domain/dashboard/invoices
,usePathname
returns"/dashboard/invoices"
.
useRouter
.- Facilitates navigating between routes within client components, offering multiple methods.
Implementation Steps Overview:
- Capture user input;
- Update the URL with search parameters;
- Keep the URL synchronized with the input field;
- Update the table to reflect the search query.
Back to the Project
1. Capture user input
- Open the
Search
component (app/ui/search.tsx
); - Observe the use of
'use client'
, indicating the availability of event listeners and hooks; - Utilize the
handleSearch
function, which triggers on every input change.
After implementing, open the Developer Console in your browser. You should see any text inputted in the input field reflected in the browser console.
2. Update the URL with search parameters
- Import the
useSearchParams
hook from'next/navigation'
and assign it to a variable; - Inside the
handleSearch
function, create a new instance ofURLSearchParams
using the previously defined variable (searchParams
). This utility provides methods to manipulate URL query parameters; - Set the parameters string based on the user's input. If the input is empty, delete it;
- Utilize
useRouter
andusePathname
hooks from'next/navigation'
and use thereplace
method fromuseRouter()
withinhandleSearch
.${pathname}
represents the current path, e.g.,"/dashboard/invoices"
;- As the user types into the search bar,
params.toString()
converts the input into a URL-friendly format; replace(${pathname}?${params.toString()})
updates the URL with the user's search data (e.g.,/dashboard/invoices?query=qwerty
).
The URL is updated without page reload, thanks to Next.js's client-side navigation.
After implementation, any text entered into the input will be reflected in the URL.
3. Keep the URL synchronized with the input field
To ensure the input field matches the URL and gets filled when shared, use defaultValue
by reading from searchParams
.
4. Update the table to reflect the search query
Finally, we update the Table
component to reflect the search query. Page components accept a prop named searchParams
. Pass the current URL params to the <Table>
component.
Don't forget to uncomment the Table
component.
Awesome! You've successfully added search functionality to your app. Give it a try – does it work? 😊
In the next chapter, we'll dive into pagination since only 6 invoices are currently visible on the page.
In Practice
Thanks for your feedback!