Skip to content

Commit 9bcad37

Browse files
authored
feat:- added back to top button (#46)
1 parent fad7283 commit 9bcad37

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

src/app/blog/[slug]/page.tsx

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ import CodeBlock from '@/components/CodeBlock';
1111
import { Callout } from '@/components/Callout';
1212
import { Alert, AlertDescription } from '@/components/Alert';
1313
import { MDXComponents } from 'mdx/types';
14+
import BackToTop from '@/components/BackToTop';
15+
1416

1517
const generateId = (children: any) => {
1618
if (Array.isArray(children)) {
@@ -73,6 +75,7 @@ export default async function BlogPost({params}: { params: { slug: string } }) {
7375
</div>
7476
</aside>
7577
</div>
78+
<BackToTop />
7679
</div>
7780
)
7881
}

src/components/BackToTop.tsx

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
"use client"
2+
3+
import { ArrowUp } from "lucide-react";
4+
import { useEffect, useState } from "react"
5+
6+
const BackToTop = () => {
7+
const [isVisible, setIsVisible] = useState(false);
8+
9+
useEffect(() => {
10+
if (typeof window === "undefined") return;
11+
12+
const handleScroll = () => {
13+
const scrolled = window.scrollY;
14+
setIsVisible(scrolled > 300);
15+
};
16+
17+
window.addEventListener('scroll', handleScroll);
18+
19+
handleScroll();
20+
21+
return () => {
22+
if (typeof window !== "undefined") {
23+
window.removeEventListener('scroll', handleScroll);
24+
}
25+
};
26+
}, []);
27+
28+
const scrollToTop = () => {
29+
if (typeof window === "undefined") return;
30+
31+
window.scrollTo({
32+
top: 0,
33+
behavior: "smooth"
34+
});
35+
};
36+
37+
return (
38+
<div className="fixed bottom-20 right-4 z-50">
39+
<button
40+
onClick={scrollToTop}
41+
className={`bg-blue-500 text-white p-3 rounded-full shadow-lg hover:bg-blue-600 transition-opacity ${isVisible ? "opacity-100" : "opacity-0 pointer-events-none"
42+
}`}
43+
>
44+
<ArrowUp />
45+
</button>
46+
</div>
47+
);
48+
};
49+
50+
export default BackToTop;

0 commit comments

Comments
 (0)