Unexpected behaviour when use Next.js router push with URL object

949 views Asked by At

According to the Next.js documentation, I can use the router push function with a URL object to route dynamic paths, like this example :

import { useRouter } from 'next/router'

export default function ReadMore({ post }) {
  const router = useRouter()

  return (
    <span
      onClick={() => {
        router.push({
          pathname: '/post/[pid]',
          query: { pid: post.id },
        })
      }}
    >
      Click here to read more
    </span>
  )
}

But, when I try use this feature, the Next.js router sends the following /post/[pid]?pid=1 to the browser (we take for example that the post id is 1), that is, the router does not replace the [pid] with the value of the query object.

Can someone help me?

1

There are 1 answers

0
UNW On

ReadMore is a kind of view component.

When you execute router using click, [pid] is replaced to post.id.

So, if you used as follows, router moves to http://localhost:3000/post/123

index.js

import ReadMore from "../../components/read-more";

export default function FirstPost() {
    return (
        <>
            <ReadMore post={{id: 123}} />
        </>
    )
}

read-more.js

import { useRouter } from 'next/router'

export default function ReadMore({ post }) {
  const router = useRouter()

  return (
    <span
      onClick={() => {
        router.push({
          pathname: '/post/[pid]',
          query: { pid: post.id },
        })
      }}
    >
      Click here to read more
    </span>
  )
}