Next Js

How to pass data from one Page to other page in Next Js

Today we will learn how to pass data from one page to other page in Next Js 13 and 14. We will do a simple example of passing data between pages. We will pass only an id from one page to other page using url query parameters.

Let’s assume we have a page that contains the list of products. From this page we want to click on a single product and navigate to single page where we can display the complete detail of this product. To fetch the complete detail of that product in next page, obviously we need id of that product. We will pass this id from the product’s list page to detail page.

Pass ID from one Page to Other Page

To pass the id from one page to other page we will use useSearchParams hook. This hook allows us to read the current’s url query string.

First we will create a page from where we have to pass id to next page.

Create a folder ‘first-page’ under the app folder, and create page.jsx in it.

"use client";
import { useRouter, useSearchParams } from "next/navigation";
import { useCallback } from "react";
export default function FirstPage() {
const searchParams = useSearchParams();
const router = useRouter();
const id = searchParams.get("id");
const handleClick = () => {
router.push("second-page?" + createQueryString("id", 10));
};
const createQueryString = useCallback(
(name, value) => {
const params = new URLSearchParams(searchParams.toString());
params.set(name, value);
return params.toString();
},
[searchParams]
);
return (

<div className="h-screen bg-white flex items-center justify-center">
<div className=" flex-col">
<h1>This is First Page</h1>
<button
type="button"
className="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 me-2 mb-2 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800"
onClick={handleClick}
>
Go to Second Page
</button>
</div>
</div>

);
}

Output

From this page we are sending an id to second page using query parameters. Now create second page where we will receive this id.

Receive data in Second Page

Create second-page folder in app folder and create a page.js in it.

"use client";
import { useSearchParams } from "next/navigation";
export default function SecondPage() {
const searchParams = useSearchParams();
const id = searchParams.get("id");
return (
<>
<div className=" flex-col h-screen bg-white flex items-center justify-center">
<h1>ID Found:</h1>
<h1>{id}</h1>
</div>
</>
);
}

Output



In this page we received id from url query parameters by using useSearchParams hook. By using this method we can pass data from one page to other in Next Js.

Leave a Reply

Your email address will not be published. Required fields are marked *