Skip to content

Commit 9c1bea3

Browse files
feat(ui): Added the Scroll to top button
1 parent 035b782 commit 9c1bea3

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/App.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { useEffect } from 'react';
22
import { RouterProvider } from 'react-router-dom';
33
import router from '@/routes';
4+
import ScrollToTop from './components/ScrollToTop';
45

56
const App = () => {
67
useEffect(() => {
@@ -24,6 +25,7 @@ const App = () => {
2425

2526
return (
2627
<div className="min-h-screen flex flex-col bg-white dark:bg-gray-900">
28+
<ScrollToTop />
2729
<RouterProvider router={router} />
2830
</div>
2931
);

src/components/ScrollToTop.tsx

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import { useEffect, useState } from 'react';
2+
3+
export default function ScrollToTop() {
4+
const [visible, setVisible] = useState(false);
5+
6+
useEffect(() => {
7+
const onScroll = () => setVisible(window.scrollY > 300);
8+
window.addEventListener('scroll', onScroll, { passive: true });
9+
onScroll();
10+
return () => window.removeEventListener('scroll', onScroll);
11+
}, []);
12+
13+
if (!visible) return null;
14+
15+
return (
16+
<button
17+
aria-label="Scroll to top"
18+
onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}
19+
style={{ zIndex: 9999 }}
20+
className="
21+
fixed right-5 bottom-6
22+
w-15 h-15 rounded-lg border-none
23+
bg-emerald-300 text-black shadow-lg
24+
cursor-pointer flex items-center justify-center
25+
opacity-95 hover:opacity-100 hover:-translate-y-[3px]
26+
transition-transform duration-200 ease-in-out
27+
focus:outline-none focus:ring-2 focus:ring-white/20 focus:ring-offset-2
28+
"
29+
>
30+
<svg
31+
xmlns="http://www.w3.org/2000/svg"
32+
stroke="currentColor"
33+
width="35"
34+
height="35"
35+
fill="currentColor"
36+
viewBox="0 0 640 640"
37+
>
38+
<path d="M342.6 81.4C330.1 68.9 309.8 68.9 297.3 81.4L137.3 241.4C124.8 253.9 124.8 274.2 137.3 286.7C149.8 299.2 170.1 299.2 182.6 286.7L288 181.3L288 552C288 569.7 302.3 584 320 584C337.7 584 352 569.7 352 552L352 181.3L457.4 286.7C469.9 299.2 490.2 299.2 502.7 286.7C515.2 274.2 515.2 253.9 502.7 241.4L342.7 81.4z" />
39+
</svg>
40+
</button>
41+
);
42+
}

0 commit comments

Comments
 (0)