2021.03.21 - [Usage/ReactJS] - Table of Contents 스크롤 메뉴 구현

 

Table of Contents 스크롤 메뉴 구현

createContext를 사용하여 provider, context 생성 Toc.js 생성 메뉴에서 이동 시킬 위치를 각각의 컴포넌트에서 pos로 받아와서 저장 시킬 예정 import React from "react"; import { createContext, useState }..

mugon-devlog.tistory.com

이전 포스트의 확장판입니다.

ToC 스크롤 메뉴가 구현되어 있다는 가정하에 시작하겠습니다.

스크롤의 현재 위치, 동적으로 구현하고픈 페이지의 상단과 하단 위치의 절대 값

//현재 위치가 이곳에 왔을때 active true
const [active, setActive] = useState(false);
const element = useRef(null);

useEffect(() => {
  const onScroll = () => {
    const scrollTop = window.pageYOffset + 100; //현재 위치
    //현재 페이지 상단
    const pagePosTop =
    element.current.getBoundingClientRect().top + window.pageYOffset;
    //현재 페이지 하단
    const pagePosBot =
    element.current.getBoundingClientRect().bottom + window.pageYOffset;
    if (pagePosTop < scrollTop && scrollTop < pagePosBot) {
      setActive(true);
    } else {
      setActive(false);
    }
  };
  if (loc !== 0) {
  	window.addEventListener("scroll", onScroll);
  }
  return () => {
  	window.removeEventListener("scroll", onScroll);
  };
}, [active]);

-------
return(
 <Page id="fourth" ref={element}>
 {* *}
 </Page>
)

스크롤이 페이지 영역에 들어왔을때 나타나게끔 css

styled-components를 이용해 active값을 받아 구현

const IconStyle = styled.img`
  width: 40rem;
  height: 15rem;
  animation: ${(props) => (props.active ? "fadein 3s" : "fadeout 3s")};
  @keyframes fadein {
    from {
      opacity: 0;
    }
    to {
      opacity: 1;
    }
  }
  @keyframes fadeout {
    from {
      opacity: 1;
    }
    to {
      opacity: 0;
    }
  }
`;
--------
return (
	<IconStyle src="./icon.png" active={active} />
);

 

 

728x90

+ Recent posts