From a43cd50166d76a10b63899876d90e37aec725db4 Mon Sep 17 00:00:00 2001 From: DefectingCat Date: Mon, 12 Dec 2022 15:24:29 +0800 Subject: [PATCH] Update scroll to top --- components/common/BackToTop.tsx | 24 ++++++++++++++++++++++-- layouts/MainLayout.tsx | 19 +------------------ lib/utils/index.ts | 16 ++++++++++++++++ 3 files changed, 39 insertions(+), 20 deletions(-) diff --git a/components/common/BackToTop.tsx b/components/common/BackToTop.tsx index c2a15c8..0713c46 100644 --- a/components/common/BackToTop.tsx +++ b/components/common/BackToTop.tsx @@ -1,6 +1,6 @@ import clsx from 'clsx'; import Button from 'components/RUA/Button'; -import { memo } from 'react'; +import { memo, useCallback, useEffect, useRef, useState } from 'react'; import { FiChevronUp } from 'react-icons/fi'; const BackToTop = () => { @@ -11,6 +11,24 @@ const BackToTop = () => { }); }; + const [showTop, setShowTop] = useState(false); + const lastScrollTop = useRef(0); + const handleScroll = useCallback(() => { + const st = window.pageYOffset || document.documentElement.scrollTop; + if (st > lastScrollTop.current || st <= 0) { + // downscroll + setShowTop(false); + } else { + // upscroll + setShowTop(true); + } + lastScrollTop.current = st <= 0 ? 0 : st; + }, []); + useEffect(() => { + window.addEventListener('scroll', handleScroll); + return () => window.removeEventListener('scroll', handleScroll); + }, [handleScroll]); + return ( <>