Auto Scroll (feat. useRef()) - React

Junghyun Park·2021년 4월 23일
0

문제상황

  • 페이지 상단 가로슬라이드의 A~Z 까지의 h1 문자 클릭 시, 하위의 해당 영역까지 자동 스크롤 하는 기능을 구현하고자 하였음
  • 바닐라 자바스크립트에서는 anchor tag 이용해서 쉽게 가능하고, React 자동 scroll 라이브러리 적용하면 쉽게 구현가능하지만, manual 하게 구현해보고자 했음
  • 대충 useRef() hooks를 활용하면, 버튼과 다른 타겟의 객체를 컨트롤 할 수 있음을 알고 있어, 적용하고자 했으나,
    map안에서 적용되면, 맨 마지막의 객체에만 ref가 할당되는 문제

<오류상황>

const scrollTopRef = useRef(0);   
...
const handleAutoScroll = (alphabet) => {
    console.log(scrollTopRef.current);
    }
...
<AlphabetOrder handleAutoScroll={handleAutoScroll} />
      <BrandsContainer>
        {alphabetArray.map((alphabet, index) => {
          return (
            <div className="wholeUnitContainer">
              <h1
                key={index}
                id={alphabet}
                ref={scrollTopRef}
                >
...

위와 같이 단순하게 scrollTopRef를 하나의 특정 값으로 할당하다보니, map을 돌면서 계속 overwritten되어, console.log에는 최종 값인 'Z'만 나옴 (아래 참조)

해결방법

  • key point는 ref를 map 안에서 돌면서, 쌓아가면서 array 형태로 만들어야 한다는 것!!

    =>아래처럼 array로 할당하고, 접근시에서 array 내 값을 접근하는 방식으로 하니 해결!!

const scrollTopRef = useRef([]);
...
const handleAutoScroll = (alphabet) => {
    const scrollYTo = scrollTopRef.current.find((item) => item.id === alphabet)
      .offsetTop;
    window.scrollTo(0, scrollYTo);
  };
...
<AlphabetOrder handleAutoScroll={handleAutoScroll} />
      <BrandsContainer>
        {alphabetArray.map((alphabet, index) => {
          return (
            <div className="wholeUnitContainer">
              <h1
                key={index}
                id={alphabet}
                ref={(ref) => {
                  scrollTopRef.current.push(ref);
                }}
              >
              ...
profile
21c Carpenter

0개의 댓글