Eddie
Eddie

Reputation: 31

Using Next router to link to a dynamically created page

Fairly new to NextJs - I am trying to link between a category index page and a dynamically created page, which is using getServerSideProps

I have created a product template page with the following path - /products/[...product]

I am trying to link to it from the index page using this code, but it is not working

import { useRouter } from "next/router";

const router = useRouter()

const handleClick = () => {
  const productUrl = `/products/${slug}`;
  router.push(productUrl);
};

The following code does work, but is not very performant

const handleClick = () => {
  const productUrl = `/products/${slug}`;
  window.location.replace(productUrl);
}

Any ideas on how to implement dynamic pages with next/router would be appreciated

Upvotes: 0

Views: 951

Answers (1)

Luke Storry
Luke Storry

Reputation: 6722

Generally, for accessibility reasons (and also to avoid perf/js issues like the one you're seeing), if a button press is meant to result in a page-change, you should use anchor tags.

In Next.Js to get performant routing, you wrap these tags in a Link:

import Link from 'next/link'

...

<Link href={`/products/${slug}`}>
  <a> See details </a>
</Link>

This will then work with the dynamic slug from props.

Upvotes: 3

Related Questions