skip to Main Content

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

Answers


  1. Chosen as BEST ANSWER

    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


  2. 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
    Login or Signup to reply.
  3. 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")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search