I have a route that contains a query parameters with hyphen:
/?previous-page=building-details
In my Page:
import EnergyEfficiency from "@/ui/energy-check/energy-efficiency"
const Page = ({
params,
searchParams,
}: {
params: { id: string }
searchParams: { modernization: string; previousPage: string }
}) => {
const { modernization, previousPage } = searchParams
console.log(previousPage) // undefined
return <EnergyEfficiency addressID={params.id} />
}
export default Page
I want to access that parameter from the page props, how can I do that?
You can easily access query params of your route using useSearchParams hook
useSearchParams is a Client Component hook that lets you read the current URL's query string.
import { useSearchParams } from 'next/navigation'
export default function Page() {
const searchParams = useSearchParams()
// url => http://localhost:3000/?previous-page=building-details
const previousPage = searchParams.get('previous-page')
console.log('previousPage', previousPage) // logs 'building-details' to the console
return (
<h1>Welcome</h1>
)
}
If a Server Component is what we talk about here, here's the way
Attention! You should be using the app folder. To implement this one, add a contact folder under the app folder and then add page.tsx file inside your new contact folder and copy paste the code below.
File Structure
const Page = ({
searchParams,
}: {
searchParams: { [key: string]: string | string[] | undefined }
}) => {
const contactWay = searchParams["contact-way"]
return (
<>
<h1>Contact Page</h1>
<h2>Contact Way: {contactWay}</h2>
</>
)
}
export default Page
Now visit http://localhost:3000/contact?contact-way=email
and see the result:
CodeSandbox: https://codesandbox.io/p/sandbox/upbeat-leaf-6scwsm?file=%2Fapp%2Fcontact%2Fpage.tsx%3A3%2C5