#Link with dynamic href
1 messages · Page 1 of 1 (latest)
In Next.js, you can use dynamic routing to create links to dynamic paths. You can use interpolation to create the path, which comes in handy for dynamic route segments.
In your case, if you want to create a link to /form/[id]/editor, you can use a template literal to include the id in the href prop of the Link component. Here's an example:
import Link from 'next/link'
function MyComponent({ id }) {
return (
<Link href={`/form/${id}/editor`} passHref>
{/* Your link content here */}
</Link>
)
}
In this example, id is a prop passed to the component. You would replace id with the actual id you want to use in your path.
Alternatively, you can use a URL object in the href prop of the Link component:
import Link from 'next/link'
function MyComponent({ id }) {
return (
<Link
href={{
pathname: '/form/[id]/editor',
query: { id: id },
}}
passHref
>
{/* Your link content here */}
</Link>
)
}
In this example, pathname is the name of the page in the pages directory, and query is an object with the dynamic segment.
Sources:
- Linking to dynamic paths (https://nextjs.org/docs/pages/building-your-application/routing/linking-and-navigating#linking-to-dynamic-paths)
- With URL Object (https://nextjs.org/docs/pages/api-reference/components/link#with-url-object)
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@heavy rain kapa.ai is still learning and improving, please let us know how it did by reacting below
Let me check the knowledge base for you. One moment! :books:
If you don't want to pass the id as a prop to the component, you can use the useRouter hook from next/router to access the router object inside your component. The router object's query property will contain the dynamic segments of the current route.
Here's an example:
import Link from 'next/link'
import { useRouter } from 'next/router'
function MyComponent() {
const router = useRouter()
const { id } = router.query
return (
<Link href={`/form/${id}/editor`} passHref>
{/* Your link content here */}
</Link>
)
}
In this example, useRouter is used to get the current route's id parameter, which is then used to create the href for the Link component.
Please note that the id will be undefined during the initial render on the server, and it will only be available after the component is mounted on the client. You might want to add some checks to ensure id is defined before using it.
Sources:
- Github Issue (closed): [Bug] next/link is not calling the server for subsequent navigations on dynamic routes > Comments Part 9 (https://github.com/vercel/next.js/issues/42991)
- Next.js Routing (https://nextjs.org/docs/routing/introduction)