본문 바로가기
FE - Tools/React

[React] useRef 이용해서 스크롤 특정 위치로 이동시키기

by thedev 2022. 12. 13.

 

useRef 이용해서 스크롤 특정 위치로 이동시키기

 


 

 바닐라 자바스크립트에서는 querySelector를 사용하여 DOM에 접근하지만 React에서는 useRef로 DOM에 접근한다. 특정 컴포넌트에 동작을 수행하고 싶다면 useRef를 이용하면 된다. 그럼 useRef를 이용하여 NavBar의 글자 클릭 시 특정 위치로 이동하는 기능을 구현해보자!

 


우선, 전체 코드는 이렇게 생겼다.

 

import React, { useRef } from "react";
import One from "./One";
import Two from "./Two";
import Three from "./Three";

export default function Home() {
  const scrollRef = useRef([]);

  const handleScrollView = (event) => {
    const name = event.target.innerText;
    const category = {
      One: 0,
      Two: 1,
      Three: 2,
    };
    scrollRef.current[category[name]].scrollIntoView({ behavior: "smooth" });
  };

  return (
    <>
      <div onClick={handleScrollView}>
        <span>One</span>
        <span>Two</span>
        <span>Three</span>
      </div>
      <div>
        <div ref={(el) => (scrollRef.current[0] = el)}>
          <One />
        </div>
        <div ref={(el) => (scrollRef.current[1] = el)}>
          <Two />
        </div>
        <div ref={(el) => (scrollRef.current[2] = el)}>
          <Three />
        </div>
      </div>
    </>
  );
}

 

 One, Two, Three는 예시 컴포넌트이다.

 

// One.js

import React from "react";

export default function One() {
  return <div style={{ height: "100vh", backgroundColor: "red" }}>One</div>;
}

 

// Two.js

import React from "react";

export default function Two() {
  return <div style={{ height: "100vh", backgroundColor: "green" }}>Two</div>;
}

 

// Three.js

import React from "react";

export default function Three() {
  return <div style={{ height: "100vh", backgroundColor: "blue" }}>Three</div>;
}

 

 <span>One</span>를 클릭하면 One 컴포넌트가 보이게 스크롤이 이동하고, <span>Two</span>를 클릭하면 Two 컴포넌트가 보이게 스크롤이 이동하고,<span>Three</span>를 클릭하면 Three 컴포넌트가 보이게 스크롤이 이동하는 기능을 구현하려 한다.

 


 

1. NavBar와 컴포넌트 작성하기

 

import React from "react";
import One from "./One";
import Two from "./Two";
import Three from "./Three";

export default function Home() {
  return (
    <>
      <div>
        <span>One</span>
        <span>Two</span>
        <span>Three</span>
      </div>
      <div>
        <One />     
        <Two />
        <Three />
      </div>
    </>
  );
}

 

One, Two, Three는 NavBar이고, 그 아래는 컴포넌트이다.

 

 

2. useRef로 변수 만들기

 

import React, { useRef } from "react";
import One from "./One";
import Two from "./Two";
import Three from "./Three";

export default function Home() {
  const scrollRef = useRef([]);

  return (
    <>
      <div>
        <span>One</span>
        <span>Two</span>
        <span>Three</span>
      </div>
      <div>
        <div ref={(el) => (scrollRef.current[0] = el)}>
          <One />
        </div>
        <div ref={(el) => (scrollRef.current[1] = el)}>
          <Two />
        </div>
        <div ref={(el) => (scrollRef.current[2] = el)}>
          <Three />
        </div>
      </div>
    </>
  );
}

 

 useRef로 변수를 생성한다. useRef를 여러 번 사용하기 위해서 배열로 선언하였다. 그리고 컴포넌트로 가서 ref를 작성해준다. 이때 <div>로 컴포넌트를 감싸고 <div>에 ref를 넣어주어야 한다.

 

 

3. 스크롤 이동 함수 만들기

 

import React, { useRef } from "react";
import One from "./One";
import Two from "./Two";
import Three from "./Three";

export default function Home() {
  const scrollRef = useRef([]);

  const handleScrollView = (event) => {
    const name = event.target.innerText;
    const category = {
      One: 0,
      Two: 1,
      Three: 2,
    };
    scrollRef.current[category[name]].scrollIntoView({ behavior: "smooth" });
  };

  return (
    <>
      <div onClick={handleScrollView}>
        <span>One</span>
        <span>Two</span>
        <span>Three</span>
      </div>
      <div>
        <div ref={(el) => (scrollRef.current[0] = el)}>
          <One />
        </div>
        <div ref={(el) => (scrollRef.current[1] = el)}>
          <Two />
        </div>
        <div ref={(el) => (scrollRef.current[2] = el)}>
          <Three />
        </div>
      </div>
    </>
  );
}

 

 scrollRef.current[category[name]].scrollIntoView({ behavior: "smooth" });라고 작성해주면 컴포넌트의 ref로 스크롤이 이동한다. behavior을 smooth로 하면 페이지가 부드럽게 이동한다. 그리고 이 함수를 NavBar에 해당하는 곳에 onClick으로 작성해준다.

 

그럼 완성!

 


 

2024. 01. 11. 업데이트

 

이 함수를 라이브러리로 배포하였습니다. 필요하시다면 사용해보세요! 😀

 

NPM: https://www.npmjs.com/package/react-moving-scroll

문서: https://react-moving-scroll.vercel.app/

 


 

참고 자료

https://ko.reactjs.org/docs/hooks-reference.html

'FE - Tools > React' 카테고리의 다른 글

[React] useParams 이용하기  (0) 2022.12.22
[React] useEffect와 useLayoutEffect의 차이  (0) 2022.12.20
[React] 가상 DOM  (0) 2022.12.05
[React] React Hooks와 useState, useEffect  (0) 2022.12.04
[React] JSX  (0) 2022.11.07