Kerem atam
Kerem atam

Reputation: 2787

Accessing Parameter from Dynamic Route in Next.js

I am new to Next.js, and setting up my routing mechanism according to documentation by arranging file structuring as : pages/questions/[id].js

I would like to know if there is cool/easier way to get matched id on my page; like in React Router (match.params.id). I don't want to parse window.location.pathname as my first option.

Upvotes: 3

Views: 11785

Answers (3)

Vitaliy Spiridonov
Vitaliy Spiridonov

Reputation: 21

Answer for those whos looking for modern solution

Since we have that info in docs

Dynamic Segments are passed as the params prop to layout, page, route, and generateMetadata functions.

Also Good to know

Since the params prop is a promise. You must use async/await or React's use function to access the values. In version 14 and earlier, params was a synchronous prop. To help with backwards compatibility, you can still access it synchronously in Next.js 15, but this behavior will be deprecated in the future.

In server components we can access params that way:

type PropsType = {
  params: Promise<{ slug: string }>;
};

const Page: FunctionComponent<PropsType> = async function Page({ params }) {
  const { slug } = await params;

  ... use slug variable as you want
}

In client components we can use:

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

Upvotes: 2

Aatmik
Aatmik

Reputation: 53

In next.js 14 we will have to use the new next/navigation hook useParams .

import { useParams } from "next/navigation";

export default function page() {

  const projectId = useParams().id;
  ...
}

Official Documentation

Upvotes: 3

Kerem atam
Kerem atam

Reputation: 2787

OK, It was just in beginning of the documentation, my bad i did't read :

import { useRouter } from 'next/router'

const Post = () => {
  const router = useRouter()
  const { pid } = router.query

  return <p>Post: {pid}</p>
}

export default Post

Upvotes: 14

Related Questions