import Link from "next/link";
import React from "react";
import { Button } from "../ui/button";
import { Card, CardContent } from "../ui/card";
import { cn } from "@/lib/utils";
import { ChevronLeft, ChevronRight, Ellipsis } from "lucide-react";
type Props = {
currentPage: number;
count: number;
perPage: number;
};
const Pagination = async ({ currentPage, count, perPage }: Props) => {
const totalPages = Math.ceil(count / perPage);
const pages = [];
const offset = 1;
for (let i = currentPage - offset; i <= currentPage + offset; i++) {
if (i >= 1 && i <= totalPages) {
pages.push(i);
}
}
await new Promise((resolve) => {
setTimeout(() => {
resolve(undefined);
});
});
if (totalPages === 1) return null;
return (
<div className="px-[2.5%]">
<Card className=" w-fit rounded-xl mx-auto">
<CardContent className="flex items-center justify-center gap-2 p-2 ">
{currentPage > 1 ? (
<Link
href={{
pathname: "/components",
query: {
page: currentPage - 1,
},
}}
>
<Button variant="ghost" className="w-10 h-10">
<ChevronLeft className="w-5 h-5 shrink-0" />
</Button>
</Link>
) : null}
{typeof count === "number" && (
<div className="flex items-center gap-2">
{pages.map((page, idx) => {
return (
<Link
key={idx}
href={{
pathname: "/components",
query: {
page,
},
}}
>
<Button
variant="outline"
className={cn(
"w-10 h-10 flex items-center justify-center rounded-lg",
page === currentPage
? "bg-accent border-accent"
: "bg-transparent"
)}
size="sm"
>
{page}
</Button>
</Link>
);
})}
</div>
)}
{currentPage < Math.ceil(count / perPage) ? (
<div className="flex items-center gap-2">
<Button
variant="ghost"
className="w-10 h-10 hover:bg-transparent cursor-default"
>
<Ellipsis className="w-5 h-5 shrink-0" />
</Button>
<Link
href={{
query: {
page: currentPage + 1,
},
}}
>
<Button variant="ghost" className="w-10 h-10">
<ChevronRight className="w-5 h-5 shrink-0" />
</Button>
</Link>
</div>
) : null}
</CardContent>
</Card>
</div>
);
};
export default Pagination;
The app I am building has filters and a search, but whenever I go to a different page, if I have a search or an active filter, those parameters are erased from the URL and all I have is the “?page=#ofPage”. I want to find a way to keep the URL parameter when I change pages with my pagination for a better user experience. Or if that is not possible, can I do it using query-string? If som how? I appreciate any help you can provide.