리스트 페이지에 두 가지 탭이 있는데
탭은 헤더 아래에 sticky로 붙이고,
스크롤 시 h1 태그 사라지고 모바일 헤더에 centerTitle 들어가게 하기
<MoHeader centerTitle={isFixed ? '헤더 타이틀' : undefined} />
safari에서 스크롤 했을 때 헤더 타이틀이 깜빡거리는 문제가 발생
❌ 문제 코드
const tabRef = useRef<HTMLDivElement>(null); useEffect(() => { const handleScroll = () => { if (tabRef.current) { const { top } = tabRef.current.getBoundingClientRect(); setIsFixed(top === 56); } }; window.addEventListener('scroll', handleScroll); return () => { window.removeEventListener('scroll', handleScroll); }; }, [setIsFixed, tabRef]);
원인은 사파리 브라우저에서 스크롤 시 바운스 현상이 나타나서
.getBoundingClientRect()
메서드로 잡은 위치가 계속 변해서 발생한 문제였다
sticky로 고정한 탭의 위치를 알면 .getBoundingClientRect()
메서드를 사용하지 않아도 되는데 더 간단한 방법을 떠올리지 못해서 계속 삽질만하다가 몇시간을 보냈다..
🆗 수정한 코드
useEffect(() => { const handleScroll = () => { const top = window.scrollY; setIsFixed(top >= 73); }; window.addEventListener('scroll', handleScroll); return () => { window.removeEventListener('scroll', handleScroll); }; }, [setIsFixed]);
useRef 사용하지 않고 window.scrollY
로 위치를 찾아 고정해주니 바운스 현상에 영향을 받지 않고 타이틀도 깜빡이지 않았다.