Skip to content

Commit a2f5ebd

Browse files
feat: make tags selectable
1 parent 5915d62 commit a2f5ebd

File tree

3 files changed

+49
-5
lines changed

3 files changed

+49
-5
lines changed

components/ArticleBlock.tsx

+1-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ export default function ArticleBlock({
2929
{tags.length != 0 ? (
3030
<div className="tags">
3131
{tags?.map((tag) => (
32-
<Tag key={tag}>{tag}</Tag>
32+
<Tag key={tag} tag={tag} />
3333
))}
3434
</div>
3535
) : null}

components/Tag.tsx

+47-4
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,52 @@
1+
"use client";
2+
13
import Link from "next/link";
2-
import { slug } from "github-slugger";
4+
import { usePathname, useRouter, useSearchParams } from "next/navigation";
35

46
interface TagProps {
5-
children: string;
7+
tag: string;
8+
children?: string;
69
}
7-
export function Tag({ children }: TagProps) {
8-
return <span className="tag">{children}</span>;
10+
11+
/**
12+
* A tag component that can be used to filter content by tag.
13+
* If no children are provided, the tag string will be displayed.
14+
*/
15+
export function Tag({ tag, children }: TagProps) {
16+
const searchParams = useSearchParams();
17+
const pathname = usePathname();
18+
const { replace } = useRouter();
19+
20+
function selectTag() {
21+
console.log("Tag selected:", tag);
22+
23+
const params = new URLSearchParams(searchParams);
24+
25+
const currentTags = params.get("tags");
26+
const tags = currentTags ? currentTags.split(" ") : [];
27+
if (tags.includes(tag)) {
28+
// Remove tag
29+
tags.splice(tags.indexOf(tag), 1);
30+
} else {
31+
// Add tag
32+
tags.push(tag);
33+
}
34+
35+
params.set("tags", tags.join(" "));
36+
// Remove tags parameter if empty
37+
if (tags.length === 0) {
38+
params.delete("tags");
39+
}
40+
replace(`${pathname}?${params.toString()}`);
41+
}
42+
43+
return children ? (
44+
<button onClick={selectTag} className="tag">
45+
{children}
46+
</button>
47+
) : (
48+
<button onClick={selectTag} className="tag">
49+
{tag}
50+
</button>
51+
);
952
}

styles/components/_tag.scss

+1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
.tag {
1010
cursor: pointer;
11+
border: none;
1112
font-family: $font-bold;
1213
font-size: 0.8rem;
1314
display: inline-block;

0 commit comments

Comments
 (0)