There are 3 different variants of params
- params
(/blog/1)
- single params
- multiple params
- searchParams
(/blog?postId=123)
- single search params
- multiple search params
- Both params and searchParams
(/blog/1?postId=123)
There are multiple ways to handle this
- For params –
useParams()
'use client'
import { useParams } from 'next/navigation'
export default function ExampleClientComponent() {
const params = useParams()
// Route -> /shop/[tag]/[item]
// URL -> /shop/shoes/nike-air-max-97
// `params` -> { tag: 'shoes', item: 'nike-air-max-97' }
console.log(params)
return <></>
}
- For searchParams –
useSearchParams()
'use client'
import { useSearchParams } from 'next/navigation'
export default function SearchBar() {
const searchParams = useSearchParams()
const search = searchParams.get('search')
// URL -> `/dashboard?search=my-project`
// `search` -> 'my-project'
return <>Search: {search}</>
}
- Both params and search Params using
any
type
'use client'
export default function BlogPost(props: any) {
// URL -> blog/a/b?param1=IamfirstParam¶m2=IamsecondParam
return <div>{props}</div>;
// Output ->
//{
// params: { blogId: [ 'a', 'b' ] },
// searchParams: { param1: 'IamfirstParam', param2: 'IamsecondParam' }
//}
}
- Both params and search Params using
defined
type
'use client';
// URL -> blog/a/b?param1=IamfirstParam¶m2=IamsecondParam
export default function BlogPost({
params,
searchParams,
}: {
params: { blogId: string[] };
searchParams: { param1: string; param2: string };
}) {
return (
<div>
{params.blogId[0]}
{params.blogId[1]}
{searchParams.param1}
{searchParams.param2}
</div>
);
}
For all possibility of dynamic params refer: How to do dynamic routes with Next.js 13?
Also refer to the latest Next.js 13 code templates
Next.js 13+ Power Snippets | TypeScript/Javascript
It includes wide range of code snippets for both ts
and js
. Find all snippets here