|
| 1 | +'use client'; |
| 2 | + |
| 3 | +import Arrow from '@/shared/assets/icons/arrow_up_24.svg'; |
| 4 | +import { useEffect, useRef } from 'react'; |
| 5 | + |
| 6 | +function ScrollTopBtn() { |
| 7 | + const animationRef = useRef<number | null>(null); |
| 8 | + |
| 9 | + // scrollTop 버튼 클릭 시 |
| 10 | + const scrollToTop = () => { |
| 11 | + const currentPosition = document.documentElement.scrollTop || document.body.scrollTop; |
| 12 | + if (currentPosition > 0) { |
| 13 | + animationRef.current = requestAnimationFrame(scrollToTop); |
| 14 | + window.scrollTo(0, currentPosition - currentPosition / 8); |
| 15 | + } |
| 16 | + }; |
| 17 | + |
| 18 | + // 사용자 스크롤 시 애니메이션 취소 |
| 19 | + useEffect(() => { |
| 20 | + const cancelScroll = () => { |
| 21 | + if (animationRef.current) { |
| 22 | + cancelAnimationFrame(animationRef.current); |
| 23 | + animationRef.current = null; |
| 24 | + } |
| 25 | + }; |
| 26 | + |
| 27 | + window.addEventListener('wheel', cancelScroll, { passive: true }); |
| 28 | + window.addEventListener('touchstart', cancelScroll, { passive: true }); |
| 29 | + |
| 30 | + return () => { |
| 31 | + window.removeEventListener('wheel', cancelScroll); |
| 32 | + window.removeEventListener('touchstart', cancelScroll); |
| 33 | + }; |
| 34 | + }, []); |
| 35 | + |
| 36 | + // if (!isVisible) return null; |
| 37 | + return ( |
| 38 | + <div className="fixed right-6 bottom-6 z-50"> |
| 39 | + <button |
| 40 | + type="button" |
| 41 | + aria-label="최상단으로 스크롤 이동" |
| 42 | + onClick={scrollToTop} |
| 43 | + className="flex-center w-10 h-10 shadow-[0_4px_12px_0_rgba(0,0,0,0.5)] bg-secondary rounded-full" |
| 44 | + > |
| 45 | + <Arrow aria-hidden /> |
| 46 | + </button> |
| 47 | + </div> |
| 48 | + ); |
| 49 | +} |
| 50 | +export default ScrollTopBtn; |
0 commit comments