Next.js Discord

Discord Forum

Dynamic Routing using app router

Unanswered
Giant panda posted this in #help-forum
Open in Discord
Giant pandaOP
I am trying to build a static site that has a table of 4 elements, lets call it A, B, C,D. Clicking on any of them will lead to another page. All 4 element should go to the same page but I want that page to know which element was clicked on. How should I do that

4 Replies

current component:

<Link href={/yourpage/${"A" || "B" || "C" etc }}/>

Then in the redirection page you can get the pathname

Redirection page:

'use client'

import { usePathname } from 'next/navigation'

const RedirectionPage = () => {
const pathname = usePathname()
return <p>Current pathname: {pathname}</p>
}

File tree could be:
- route1
- page.tsx (where u have the link component)
- yourpage
- [id]
- page.tsx (redirection page, the id serves as the reference which element was clicked)
@Giant panda I am trying to build a static site that has a table of 4 elements, lets call it A, B, C,D. Clicking on any of them will lead to another page. All 4 element should go to the same page but I want that page to know which element was clicked on. How should I do that
Turkish Van
You can do that and keep that page a Server component also.

Either pass a clicked element value as a searchParam like this:
<Link href={"/your/super/cool/page?something=A"}>Go to A</Link>

Then You can access it in a Page like this:
const Page = ({searchParams}) => {
    const passedValue = searchParams?.["something"];
    // passedValue is equal to 'A'
}

Docs: https://nextjs.org/docs/app/api-reference/file-conventions/page#searchparams-optional

The second way would be making it a Dynamic route. Take a look at docs:
https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes