hellomello
hellomello

Reputation: 8587

Next.js prepending current path for nested dynamic routes in Link components

How would you go about dealing with nested dynamic routes and using Next.js Link component?

Say I have 2 file paths:

/pages/projects/index.js
<Link href={`/projects/${project.id}`} key={index}>
  <a>Project Name</a>
</Link>

This will take me to localhost:3000/projects/some-id/

and

/pages/projects/[pid]/index.js

This is where I'm having trouble figuring out how to prepend the path of localhost:3000/projects/some-id/

<Link href={`/${router.pathname}/apple`}>
  <a>Business name</a>
</Link>

If I use router.pathname, I get /projects/[pid]/apple, and its missing the domain name, if I use router.asPath, I get the correct path, but its still missing the domain. I don't know if this is the correct way, because i shouldn't be adding the domain name into Link's href.

Upvotes: 1

Views: 5755

Answers (1)

Ryan Le
Ryan Le

Reputation: 8412

For a nested dynamic route in Nextjs, you could set up your project like so:

enter image description here

Starting with a simple link in index.js

import Link from 'next/link';

export default function Index() {
  return (
    <section>
      <h2>Index</h2>
      <Link href="/projectA">
        <a>Project A</a>
      </Link>
    </section>
  );
}

Once you are in [projectId].js use useRouter to get current param and append to your next route

import Link from 'next/link';
import { useRouter } from 'next/router';

export default function Project() {
  const router = useRouter();
  const { projectId } = router.query;
  return (
    <section>
      <Link href={`/${projectId}/2`}>
        <a>Project 2</a>
      </Link>
    </section>
  );
}

Working example

Upvotes: 2

Related Questions