How to pass page number in url in nextjs?

At first declare a function handlePageChange()

code:

const handlePageChange = (count) => {

// Update the state of currentPage and filters

setCurrentPage(count);

params.set(‘m_page’, count);

window.history.replaceState({}, , `${window.location.pathname}?${params}`);

};

And handlePageChange

code:

<div className=“flex justify-between items-center screen-xs:mx-0 mx-4 p-4 px-8”>

<button

onClick={() => handlePageChange(currentPage1)}

disabled={currentPage === 1}

className=“border border-gray-300 px-4 py-2 rounded-md text-sm font-medium text-gray-500 hover:bg-cyan-900 hover:text-white focus:outline-none”

>

Previous

</button>

<div className=“dark:text-black”>

{currentPage}/{Math.ceil(totalItemCount / resourcesPerPage)}

</div>

<button

onClick={() => handlePageChange(currentPage + 1)}

disabled={indexOfLastResource >= totalItemCount}

className=“border border-gray-300 px-4 py-2 rounded-md text-sm font-medium text-gray-500 hover:bg-cyan-900 hover:text-white focus:outline-none”

>

Next

</button>

</div>

by doing this it will be as shown in the url as shown in the screenshot:

if we add the below code in the useeffect than when we reload, it will be comeback in the page where we were standing:

code:

// Check if ‘m_page’ query parameter exists and set currentPage accordingly

const pageParam = parseInt(params.get(‘m_page’));

if (!isNaN(pageParam)) {

setCurrentPage(pageParam);

}

Leave a comment

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