Skip to content

Commit cf4fada

Browse files
committed
add back to top button
1 parent 982f7c6 commit cf4fada

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

src/components/BackToTopButton.tsx

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import React, { useState, useEffect, useCallback } from "react";
2+
3+
const BackToTopButton: React.FC = () => {
4+
const [isVisible, setIsVisible] = useState(false);
5+
6+
const toggleVisibility = useCallback(() => {
7+
if (window.scrollY > 300) {
8+
setIsVisible(true);
9+
} else {
10+
setIsVisible(false);
11+
}
12+
}, []);
13+
14+
const scrollToTop = () => {
15+
window.scrollTo({
16+
top: 0,
17+
behavior: "smooth",
18+
});
19+
};
20+
21+
useEffect(() => {
22+
window.addEventListener("scroll", toggleVisibility);
23+
return () => {
24+
window.removeEventListener("scroll", toggleVisibility);
25+
};
26+
}, [toggleVisibility]);
27+
28+
return (
29+
<div className="fixed bottom-4 right-4 z-50 hidden md:block">
30+
{isVisible && (
31+
<button
32+
onClick={scrollToTop}
33+
className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-full shadow-lg transition-opacity duration-300 ease-in-out opacity-75 hover:opacity-100"
34+
aria-label="Scroll to top"
35+
>
36+
37+
</button>
38+
)}
39+
</div>
40+
);
41+
};
42+
43+
export default BackToTopButton;

src/components/Feed.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import PollData from "./PollData";
2626
import { RedditApiClient } from "../api/RedditApiClient";
2727
import { useNavigate, useParams } from "react-router-dom";
2828
import SegmentedControl from "./SegmentedControl";
29+
import BackToTopButton from "./BackToTopButton";
2930

3031
export interface FeedProps {
3132
subreddit: string;
@@ -289,6 +290,7 @@ const Feed: React.FC<FeedProps> = memo(({ subreddit, initialTime, initialSort })
289290
))}
290291
</div>
291292
<div ref={sentinel} className="h-1"></div>{" "}
293+
<BackToTopButton />
292294
</div>
293295
</div>
294296
);

0 commit comments

Comments
 (0)