Mathias Riis Sorensen
Mathias Riis Sorensen

Reputation: 850

Next.js Link and paths

I have a popover menu in my header displaying products. When clicking on the first one, regardless of which one on the list, it navigates correctly to the path "products/some-product". But if I'm on one of the product pages already, and I'm trying to navigate to another product it adds the "products/" again in the URL. E.g. "products/products/some-product".

I'm using Next.js 11 and Link.

Below is part of my code handling the list of products with navigation:

<div>
{products.map((item) => (
    <Link href={`products/${item.href}`}>
    <a
        key={item.name}
        >
        <div>
        <item.icon
            aria-hidden="true"
        />
        </div>
        <div>
        <p>
            {item.name}
        </p>
        <p>
            {item.description}
        </p>
        </div>
    </a>
    </Link>
))}
</div>

I have a menuData.jsx component to keep track of all my products, which I then import to the file above. Here is an example from the menuData.jsx file:

export const products = [
  {
    name: "some-product",
    description:
      "Some description",
    icon: CheckIcon,
  },
]

Can you spot what I'm doing wrong? :)

Upvotes: 9

Views: 6714

Answers (1)

fjc
fjc

Reputation: 5815

Just add a / in front of products in the href:

<Link href={`/products/${item.href}`}>

You are linking to relative paths, which, when you are on /products, will be /products/products:

Upvotes: 13

Related Questions