#add search param on server page
1 messages · Page 1 of 1 (latest)
Hi @worn pecan. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Yes, you can add search parameters programmatically in your page.tsx file using Next.js. You can use the useSearchParams hook to access the search parameters. However, please note that searchParams is a dynamic API whose values cannot be known ahead of time. Using it will opt the page into dynamic rendering at request time.
Here is an example of how you can use useSearchParams in your page.tsx file:
import { useSearchParams } from 'next/navigation'
export default function Page() {
const searchParams = useSearchParams()
const search = searchParams.get('search')
// This will be logged on the server during the initial render
// and on the client on subsequent navigations.
console.log(search)
return <>Search: {search}</>
}
In this example, useSearchParams is used to get the 'search' parameter from the URL. If you want to add a search parameter when the page opens, you can use the useRouter hook or the Link component to set new searchParams. Here is an example:
import { useRouter } from 'next/router'
import { useSearchParams } from 'next/navigation'
export default function ExampleClientComponent() {
const router = useRouter()
const pathname = usePathname()
const searchParams = useSearchParams()!
const createQueryString = useCallback(
(name: string, value: string) => {
const params = new URLSearchParams(searchParams)
params.set(name, value)
return params.toString()
},
[searchParams]
)
useEffect(() => {
// Set initial search param when the page opens
router.push(pathname + '?' + createQueryString('initialParam', 'initialValue'))
}, [])
return (
// Your component code here
)
}
In this example, the useEffect hook is used to set an initial search parameter when the page opens. The createQueryString function is used to create a new query string with the initial search parameter.
Please note that the useSearchParams hook is only available on the client side. If you want to access search parameters on the server side, you can use the searchParams prop in your page.tsx file.