#Pass user input (from client component) to a fetch request (in a server component)
1 messages · Page 1 of 1 (latest)
Hi @frozen bone. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To create a search box component in Next.js that passes user input from a client component to a server component, you can follow these steps:
-
Create a Client Component for the Search Box
This component will handle user input and pass it to a server component. Here's a simple example:
// SearchBox.js (Client Component) 'use client' function SearchBox({ onSearch }) { async function handleSearch(event) { event.preventDefault(); const searchTerm = event.target.elements.search.value; await onSearch(searchTerm); } return ( <form onSubmit={handleSearch}> <input type="text" name="search" /> <button type="submit">Search</button> </form> ); } -
Create a Server Component to Handle the Search
This component will receive the search term from the client component and use it to query the database. Here's a simple example:
// SearchResults.js (Server Component) import { db } from '@utils/database' export async function SearchResults({ searchTerm }) { const results = await db.query(searchTerm); // Render the results... } -
Pass the Server Action as a Prop to the Client Component
You can pass the server action (the function that queries the database) as a prop to the client component. Here's how you can do it:
// Page.js (Server Component) import SearchBox from './SearchBox' import SearchResults from './SearchResults' function Page() { async function handleSearch(searchTerm) { 'use server' return <SearchResults searchTerm={searchTerm} /> } return <SearchBox onSearch={handleSearch} /> }
In this setup, when a user submits the search form in the SearchBox component, the handleSearch function is called with the search term. This function is a server action that returns the SearchResults component with the search term as a prop. The SearchResults component then queries the database with the search term and renders the results.
Please note that this is a simplified example and you might need to adjust it according to your specific needs and setup. For more information, you can refer to the Next.js documentation (https://nextjs.org/docs/getting-started/react-essentials).
Also, remember that Server Components are still experimental in Next.js and their usage might change in future versions of the framework.
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@frozen bone kapa.ai is still learning and improving, please let us how it did by reacting below