[react] scroll up button 기록

이재정·2022년 12월 26일
//현재 스크롤 위치를 반영할 state
const [nowScroll, setNowScroll] = useState(0);

//버튼 활성화 여부를 판단할 state
const [btnActive, setBtnActive] = useState(false);

//버튼을 눌렀을 때 가장 최상위 scroll로 가게 할 함수
const scrollUp = () => {
  window.scrollTo({ top: 0, behavior: "smooth" });
};

//스크롤을 하면서 자연스럽게 이벤트가 나오기 위해 useEffect 사용
useEffect(() => {

  //scroll 이벤트 mount
  window.addEventListener("scroll", () => {
    setNowScroll(window.scrollY);
  });
  
  // 스크롤이 일정 위치 이하일 때 버튼이 활성화되도록 진행
  if (nowScroll > 1000) {
    setBtnActive(true);
  } else {
    setBtnActive(false);
  }
  
  // return으로 이벤트 unmount
  return () => {
    window.removeEventListener("scroll", () => {
      setNowScroll(window.scrollY);
    });
  };
  
}, [nowScroll]);
profile
개발자 지망생

0개의 댓글