How to use params and searchParams in Nextjs 13
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>
);
}
Server Components
In order to get params
and searchParams
in server side component using typescript in Next.js 13, you should define what params and searchParams do you expect. For example:
// /app/category/[slug]/page.tsx
// Request URL localhost:3000/category/news?page=2
export default function PostsCategory({ params, searchParams }: { params: { slug: string }; searchParams: { page: string } }) {
const posts = getPostsByTag(params.slug, ['title', 'date', 'excerpt', 'image', 'slug', 'tags']);
const currentPage = searchParams && searchParams.page ? Number(searchParams.page) : 1;
const { slug } = params;
return (
<main>
<PaginatedPosts posts={posts} page={currentPage} title={`${slug}`} />
</main>
);
}