Skip to content

Commit

Permalink
add scroll to top button
Browse files Browse the repository at this point in the history
  • Loading branch information
alim1496 committed May 22, 2024
1 parent f5a8bfe commit 6c88d42
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import Wishlist from "./pages/Wishlist";
import ProtectedRoute from "./components/ProtectedRoute";
import Profile from "./pages/Profile";
import AllProducts from "./pages/AllProducts";
import ScrollToTopButton from "./components/ScrollToTopButton";

function App() {
return (
Expand All @@ -33,6 +34,7 @@ function App() {
<Footer />
<Cart />
<LoginModal />
<ScrollToTopButton />
</Provider>
);
}
Expand Down
41 changes: 41 additions & 0 deletions src/components/ScrollToTopButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import React, { useState, useEffect } from "react";
import { IoIosArrowUp } from "react-icons/io";

const ScrollToTopButton: React.FC = () => {
const [isVisible, setIsVisible] = useState(false);

const toggleVisibility = () => {
if (window.scrollY > 300) {
setIsVisible(true);
} else {
setIsVisible(false);
}
};

const scrollToTop = () => {
window.scrollTo({
top: 0,
behavior: "smooth",
});
};

useEffect(() => {
window.addEventListener("scroll", toggleVisibility);
return () => window.removeEventListener("scroll", toggleVisibility);
}, []);

return (
<div className="fixed bottom-10 right-8 z-50">
{isVisible && (
<button
onClick={scrollToTop}
className="bg-gray-800 text-white rounded-full h-10 w-10 shadow-md hover:bg-gray-700 transition-opacity duration-300 opacity-50 hover:opacity-100"
>
<IoIosArrowUp size={30} className="m-auto" />
</button>
)}
</div>
);
};

export default ScrollToTopButton;

0 comments on commit 6c88d42

Please sign in to comment.