2

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;
1

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

"use client" was added actually as the error goes
Ah I've checked the docs. The query object has been removed. You can use useSearchParams instead. nextjs.org/docs/app/api-reference/functions/use-search-params
2

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")

Comments

-1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.