From 14eb853e7b1cd4f051a3679686d26a7401f15bc5 Mon Sep 17 00:00:00 2001 From: sharad Date: Fri, 18 Oct 2024 21:38:41 +0530 Subject: [PATCH] Added scroll to top button --- src/core/components/app.jsx | 8 ++- src/core/components/scroll-to-top.jsx | 85 +++++++++++++++++++++++++++ 2 files changed, 92 insertions(+), 1 deletion(-) create mode 100644 src/core/components/scroll-to-top.jsx diff --git a/src/core/components/app.jsx b/src/core/components/app.jsx index fcc09918aea..659ffc0f30d 100644 --- a/src/core/components/app.jsx +++ b/src/core/components/app.jsx @@ -3,6 +3,7 @@ */ import React from "react" import PropTypes from "prop-types" +import ScrollToTopButton from "./scroll-to-top" class App extends React.Component { getLayout() { @@ -18,7 +19,12 @@ class App extends React.Component { render() { const Layout = this.getLayout() - return + return ( + <> + + + + ) } } diff --git a/src/core/components/scroll-to-top.jsx b/src/core/components/scroll-to-top.jsx new file mode 100644 index 00000000000..c696f3054f8 --- /dev/null +++ b/src/core/components/scroll-to-top.jsx @@ -0,0 +1,85 @@ +import React, { useState, useEffect } from "react" + +const ScrollToTopButton = () => { + const [isVisible, setIsVisible] = useState(false) + const [hideTimeout, setHideTimeout] = useState(null) + + const styles = { + button: { + position: "fixed", + bottom: "20px", + right: "20px", + padding: "10px 20px", + fontSize: "18px", + backgroundColor: "rgba(125, 132, 146, 0.8)", + color: "#fff", + border: "2px solid rgba(125, 132, 146, 0.8)", + borderRadius: "5px", + cursor: "pointer", + boxShadow: "0px 4px 6px rgba(0, 0, 0, 0.1), 0 0 15px rgba(125, 132, 146, 0.6)", + transition: "opacity 0.5s ease, box-shadow 0.3s ease", + opacity: isVisible ? 1 : 0, + pointerEvents: isVisible ? "auto" : "none", + }, + icon: { + width: "20px", + height: "20px", + fill: "#fff", + }, + } + + const toggleVisibility = () => { + if (window.scrollY > 300) { + setIsVisible(true) + + if (hideTimeout) { + clearTimeout(hideTimeout) + } + + const timeout = setTimeout(() => { + setIsVisible(false) + }, 3000) + + setHideTimeout(timeout) + } else { + setIsVisible(false) + } + } + + const scrollToTop = () => { + window.scrollTo({ + top: 0, + behavior: "smooth", + }) + } + + useEffect(() => { + window.addEventListener("scroll", toggleVisibility) + + return () => { + window.removeEventListener("scroll", toggleVisibility) + if (hideTimeout) { + clearTimeout(hideTimeout) + } + } + }, [hideTimeout]) + + return ( +
+ {isVisible && ( + + )} +
+ ) +} + +export default ScrollToTopButton