Search code examples
next.jsparameters

how to get "params" in a client component in Next13?


I know that we can get query parameters i-e (/home?id=1) via the useSearchParams hook, I want to get /home/[id] in a client component, as before we were using the next/router router.query, but in next/navigation that is no longer supported.

In a server component, I can get them by using the prop param but how do I get them in a client component?

I tried using the router.query but that is longer supported in the next13 directory and has to use the next/navigation.


Solution

  • It seems like there will be a useParams hook in the future, but for the time being the section on the beta docs seems to be grayed out.

    So you've got two options:

    Pass the params down from the server component to the child client component:

    // app/page.js
    export default function Page({ params }) {
      return (
        <ClientComponent params={params} />
      )
    }
    
    // app/ClientComponent.js
    "use client"
    
    export default function ClientComponent({ params }) {
      // use `params` here
    }
    

    Or use some of the other hooks like usePathname or useSelectedLayoutSegment to extract the id from the url. For example, if your dynamic url is /home/[id], usePathname will return /home/1 if the url is /home/1, so you can strip the /home/ part to get the id.