Handling Params and Queries in Next.js 14

Handling Params and Queries in Next.js 14

Next.js 13 introduces improvements in handling dynamic routes and parameters, making it even easier to build dynamic and personalized experiences for our users.

Params and Dynamic Pages

Here is how we can pass a parameter to the dynamic page path in the Link Component:

<Link href={`/path/${id}`}></Link>        

Now, we have to create a dynamic route and access the id there. Simply go to the app directory and create a page with the syntax [id]/page.js

Inside the page, you can now access that id with the useParams hook:

const params = useParams();
const { id } = params;        

Now you can use this id to fetch data from the server or perform any desired actions with it. The page is now dynamic.

Query a Parameter

We can query a parameter to a specific page that will be shown in the URL and accessed on that page. Here is how we can do this:

<Link href={`/path?id=${id}`}></Link>        

Pro Tip

The hooks are only usable in the client component. So, what if you want to access these parameters in a server-side component? For that, Nextjs gives us a very easy way to do it.

In the page component props, we have searchParams and params, then we can use these props to access parameters and query parameters:

const Page = async ({ params: { id }, searchParams }) => {
    return (
        // JSX
    );
}        
Mukhi Talibhusain

JavaScript || React Js || Express Js || Next Js || Mongo DB

10 个月

Thanks for posting

Aizaz Ali Shah

Computer vision | Machine learning | Deep learning | Classification | Detection | Segmentation | Student at Islamia college university Peshawar

1 年

??

要查看或添加评论,请登录

Wali Ullah的更多文章

社区洞察

其他会员也浏览了