GitHub Stars Button
A beautiful button that displays your GitHub repository star count with real-time data fetching.
Category
ButtonReact
CSS
Tailwind
Manual
Create a file and paste the following code into it.
github-stars-button.tsx
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
"use client";
import { StarFilledIcon } from "@radix-ui/react-icons";
import { useEffect, useState } from "react";
import { Github } from "@/components/icons/social-icons";
import { RaisedButton } from "@/registry/new-york/ui/raised-button";
interface GitHubRepo {
stargazers_count: number;
html_url: string;
name: string;
full_name: string;
}
interface GitHubStarsButtonProps {
repo: string;
showLabel?: boolean;
size?: "sm" | "default" | "lg";
className?: string;
}
export function GitHubStarsButton({
repo,
showLabel = true,
size = "sm",
className,
}: GitHubStarsButtonProps) {
const [starCount, setStarCount] = useState<number | null>(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
let isMounted = true;
async function fetchStars() {
try {
const response = await fetch(`https://api.github.com/repos/${repo}`);
if (!response.ok) {
throw new Error("Failed to fetch repository data");
}
const data: GitHubRepo = await response.json();
if (isMounted) {
setStarCount(data.stargazers_count);
setIsLoading(false);
}
} catch (error) {
console.error("Error fetching GitHub stars:", error);
if (isMounted) {
setIsLoading(false);
}
}
}
fetchStars();
return () => {
isMounted = false;
};
}, [repo]);
return (
<a
href={`https://github.com/${repo}`}
target="_blank"
rel="noopener noreferrer"
>
<RaisedButton
size={size}
className={`group rounded-xl border-0! ${className || ""}`}
color="#1c1c1c"
>
<div className="flex items-center">
<Github />
{showLabel && <span className="ml-1">GitHub</span>}
</div>
<div className="flex items-center gap-1 text-sm">
<StarFilledIcon className="relative top-px size-4 text-white group-hover:text-yellow-300" />
<span className="font-medium text-white">
{isLoading ? "..." : starCount || "0"}
</span>
</div>
</RaisedButton>
</a>
);
}
Update the import paths to match your project setup.