forked from Nutlope/llamacoder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnew-link.tsx
More file actions
44 lines (36 loc) · 1.01 KB
/
Copy pathnew-link.tsx
File metadata and controls
44 lines (36 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
"use client";
import Link from "next/link";
import { usePathname, useSearchParams } from "next/navigation";
import { ComponentProps } from "react";
type NewLinkProps = {
newQuery?: Record<string, string | number | null>;
href?: string;
};
export default function NewLink({
href,
newQuery,
children,
...props
}: Omit<ComponentProps<typeof Link>, "href"> & NewLinkProps) {
const searchParams = useSearchParams();
const pathname = usePathname();
let finalHref = href || pathname;
if (newQuery) {
const params = new URLSearchParams(searchParams.toString());
// Then, add new params from newQuery
Object.entries(newQuery).forEach(([key, value]) => {
if (value) {
params.set(key, value.toString());
} else if (value === null) {
params.delete(key);
}
});
const queryString = params.toString();
finalHref = `${finalHref}${queryString ? `?${queryString}` : ""}`;
}
return (
<Link href={finalHref} {...props}>
{children}
</Link>
);
}