[useRef] 메뉴를 클릭하면 해당 섹션으로 이동 -2-

piper ·2024년 2월 12일
0

React

목록 보기
7/22

첫번째 방법을 사용하려고 했는데 header에 메뉴를 클릭해야 하는 부분이 있고
랜더링 되는 컴포넌트는 다른 컴포넌트에 있어서 막혔다.
방법은 1)최상위 컴포넌트에서 로직을 만들고
2) testRef와
3) onClick 버튼을 해당하는 컴포넌트에 props로 전달해주는 것이었다.

이 작업에서 최상위 단은 main.jsx이다.
여기에 useRef => dom에 현재 위치를 표시해주는 레퍼런스을 각기 컴포넌트에 props로
넘겨주고
onClick 이벤트는 header에 넘겨준다. header에는 3개의 span이 있기 때문에
여기에서 함수의 조건문을 유용하게 사용할 수 있다.

const Main = () => {
  const testRef = useRef();
  console.log(testRef.current);

  const onClickRef = (section) => {
    if (section === "banner") {
      testRef.current.scrollIntoView({ behavior: "smooth" });
    }
  };

  return (
    <div>
      <Header onClickRef={onClickRef} />
      <Banner testRef={testRef} />
      <ToDoList />
      <Footer />
    </div>
  );
};

export default Main;
const Banner = ({testRef}) => {
  return (
    <BannerWrapper id="mainSection">
      <img src={ball} alt="ball" ref={testRef}/>
      <BannerText >Just Do it ! </BannerText>
    </BannerWrapper>
  );
};

export default Banner;
const Header = ({onClickRef}) => {
  const clickHeaderButton = (id,offset=80)=>{
    const section= document.getElementById(id)

    if (section){
      const sectionPosition=section.offsetTop;
      window.scrollTo({
        top: sectionPosition-offset,
        behavior: "smooth",
      });
    console.log(sectionPosition)
    
  }}
  
  return (
    <>
      <HeaderLayer>
        <Title>My task</Title>
        <MenuLayer>
          <span
          onClick={() => {
            onClickRef('banner')

          //   clickHeaderButton('mainSection',99)
            // const mainSection= document.getElementById("mainSection")

            // if (mainSection){
            //   const mainPosition=mainSection.offsetTop;
            //   window.scrollTo({
            //     top: mainPosition-99,
            //     behavior: "smooth",
            //   });
            // console.log(mainPosition)
            
          //   }}
          }}
          // onClick={()=>{
          //   clickButton('banner');
          // }}
          
          >
          Home
          </span>
          <span
          onClick={() => {
          //   const addSection = document.getElementById("addTodoSection");

          //   if (addSection) {
          //     const targetPosition = addSection.offsetTop;

          //     window.scrollTo({
          //       top: targetPosition-80,
          //       behavior: "smooth",
          //     });
          //   }
          // }}
          // onClick={()=>{
          //   clickButton('addTodo');
          // }}
          clickHeaderButton('addTodoSection')
        
        }}
          
          
          
          
          >  Add Task
          </span>
          <span
           onClick={() => {
            const todoSection = document.getElementById("myTodoSection");

            if (todoSection) {
              const targetPosition = todoSection.offsetTop;

              window.scrollTo({
                top: targetPosition-80,
                behavior: "smooth",
              });
            console.log(targetPosition)
            
            }
          }}
        >
        My Todo</span>
          <span
          onClick={()=>{
            clickHeaderButton('myTodaySection')
          }}
          >
            Today I Learn</span>
        </MenuLayer>
      </HeaderLayer>
    </>
  );
};

export default Header;
profile
연습일지

0개의 댓글