Burger Sasha
Burger Sasha

Reputation: 175

How to navigate to subpages?

From my understanding NEXT should be automatically generating the routes based on my folder structure.

I am mapping over article posts on news/index.tsx page but the urls I get are localhost3000/article-one when I need localhost3000/news/article-one

Can anyone point out where I'm going wrong?

{page?.articles.map((post, i) => {
      return (
          <Link
            key={i}
            href={post?.slug.current!}
          >
            {post?.title!}
          </Link>
      )
})}

Folder structure:

- pages
  - news
    - index.tsx
    - [slug].tsx

EDIT Addiction info: Slugs are being pulled from Sanity headless CMS. Tutorials often show routing by prepending news/ to the slug but this in turn is prepending news/ to all slugs

Upvotes: 0

Views: 1647

Answers (3)

Burger Sasha
Burger Sasha

Reputation: 175

Turns out to be a really simple fix..

The nav links that were getting /news/news prepended to their slugs needed a / prepended before them

Upvotes: 1

Pablopvsky
Pablopvsky

Reputation: 247

You can handle the dynamic routes in Next js in few ways, one of those is with With URL Object:

{page?.articles.map((post, i) => {
      return (
          <Link
            key={i}
            href={{
              pathname: '/news/[slug]',
              query: { slug: post?.slug?.current },
            }}
          >
            <a>
              {post?.title!}
            </a>
          </Link>
      )
})}

Additional disclaimer. You always must add the anchor <a>...</a> as a child of Link Component.

Documentation: https://nextjs.org/docs/api-reference/next/link#with-url-object

Upvotes: 1

Ali AlHussain
Ali AlHussain

Reputation: 236

From what I understand you should change your code to have the correct href:

{page?.articles.map((post, i) => {
  return (
      <Link
        key={i}
        href={`/news${post?.slug.current!}`}
      >
        {post?.title!}
      </Link>
  )
})}

Upvotes: 0

Related Questions