Next.js link component send parameter = undefined

95 views Asked by At

How can I pass parameters to a component using the Link component? The following doesn't work. I always get undefined in SinglePost.

   <Link
      key={2}
      href={{
        pathname: "/singlePost",
        query: 2,
      }}
      id={2}
    >
      <Post></Post>
    </Link>

SinglePost

export default function SinglePost() {
const router = useRouter();
const data = router.query;
//always undefined
console.log(data);

 ...

}
1

There are 1 answers

0
Nafi Asib On BEST ANSWER

If you are using Next.js 13 app router, then you can achieve this by the following approach

   <Link
      key={2}
      href={{
        pathname: "/singlePost",
        query: {id: 2},
      }}
      id={2}
    >
      <Post></Post>
    </Link>

SinglePost

'use client';
import { useSearchParams } from 'next/navigation';

// ...rest of your imports

export default function SinglePost() {
  const id = useSearchParams().get('id');
  console.log(id);

 ...

}