본문 바로가기

Study/실무

useRef 를 사용하여 scrollEvent 만들기

 
 

 

Ref 란?

  • reference의 약자로 참조라는 뜻입니다.
  • DOM을 직접 참조하기 위해 사용합니다.
  • Ref를 사용하여 element가 참조하는 변수에 접근해 변경하고, element를 제어할 수 있습니다.

 

 

ref의 장점

  • 컴포넌트를 재사용했을 때 id를 사용하면 유일해야 하는 id 는 더이상 유일하지 않고, 문제가 생길 수 있습니다.

 

 

ref를 사용해야 할 때

  • 스크롤 이벤트
  • 포커스, 텍스트, 미디어 재생 관리 등
  • canvas ...

 

 

useRef 사용하여 스크롤 이벤트 만들기

const Test = () => {
  const scrollRef = React.useRef(); // ref 변수 선언

  const scrollToTop = () => {
    const { scrollHeight, clientHeight } = scrollRef.current;
    scrollRef.current.scrollTop = clientHeight - scrollHeight;
  };
  
  const scrollToBtm = () => {
    const { scrollHeight, clientHeight } = scrollRef.current;
    scrollRef.current.scrollTop = scrollHeight - clientHeight;
  };
  
  
  // scrollTop: 세로 스크롤바 위치
  // scrollHeight: 스크롤이 있는 박스 안 div 높이
  // clientHeight: 스크롤이 있는 박스 높이
  
  return (
    <>
      <Outer ref={boxRef}>
        <Inner/>
      </Outer>
      <button type="button" onClick={scrollTop}>
        맨 위로
      </button>
       <button type="button" onClick={scrollToBtm}>
        맨 밑으로
      </button>
    </>
  );
}

export default Test;