next.jsapp-routernextjs-dynamic-routing

Next.js dynamic routing in client side page


I'm fairly new to Next.js and I've been trying to implement dynamic routing to one of my pages. Following the docs, it says to add the prop params to the page as a promise that returns the param like this:

export default async function Page({
  params,
}: {
  params: Promise<{ slug: string }>
}) {
  const slug = (await params).slug
  return <div>My Post: {slug}</div>
}

But the problem I now run into is that I can't make this a client-side component (add any state variable) because it is an asynchronous component and so I end up with the following error:

Error: async/await is not yet supported in Client Components, only Server Components.

I don't understand why params needs to be a promise. Is there a way to handle dynamic routing in a client side component page?


Solution

  • I will assume you're working with nextjs 13.4+ and its app router.

    I'd suggest using the useParam hook as referenced here in the related documentation

    useParam is a Client Component hook that lets you read a route's dynamic params filled in by the current URL.

    Example

    'use client'
     
    import { useParams } from 'next/navigation'
     
    export default function ExampleClientComponent() {
      const params = useParams<{ tag: string; item: string }>()
     
      // Route -> /shop/[tag]/[item]
      // URL -> /shop/shoes/nike-air-max-97
      // `params` -> { tag: 'shoes', item: 'nike-air-max-97' }
      console.log(params)
     
      return '...'
    }