1

This was the way to do it using Pages Router

import { useRouter } from "next/router";

import React from "react";

function ShowroomListings({}) {
  const router = useRouter();
  const { listingId } = router.query as { listingId: string };

  return <div>This is item No. {listingId}</div>;
}

export default ShowroomListings;

Failed to compile message

Now I imported useRouter from "next/navigation" this time, but '.query' will not work anymore

import { useRouter } from "next/navigation";

import React from "react";

function ShowroomListings({}) {
  const router = useRouter();
  const { listingId } = router.query as { listingId: string };

  return <div>This is item No. {listingId}</div>;
}

export default ShowroomListings;

3 Answers3

1

useRouter only works on client-component (while your component is a server-component). You can add 'use client' directive to top of the file to use useRouter.

Update:

  • The query object has been removed and is replaced by useSearchParams

Reference:

  1. Next.js useRouter
  2. Next.js 'use client' directive
  3. Next.js useSearchParams
Nhan Luong
  • 41
  • 4
0

it worked for me

import React from "react";

type ShowroomProps = {
  params: {
    listingId: string;
  };
};

export default function ShowroomListings({
  params: { listingId },
}: ShowroomProps) {
  return <div>This is item No. {listingId}</div>;
}

just passing the right dynamic route value

0

You cannot use useRouter hook in server component, because it is a client side hook. You need to make you component client inorder to get query parameters.

'use client'

also nextjs introduce new hook for query parameters which is useSearchParams, you can easily get query param with.

const params = useSearchParms()
params.get("query-parameter-name")
Ahsan Khan
  • 157
  • 2
  • 3