반응형

useRef를 사용해서 스크롤을 이동시키는 방법입니다.

 

App.js

import { useRef } from "react";

const App = () => {

    const scrollRef = useRef(null);

    const move = () => {
        scrollRef.current.scrollIntoView({ behavior: 'smooth' });
    };

    return (
        <>
            <div ref={scrollRef}>여기로 이동합니다.</div>
            
            <button onClick={move}>버튼을 누르면</button>
        </>
    );
};


export default App;

- ScrollIntoView

특정 엘리먼트 위치로 스크롤을 이동시켜주는 내장메서드입니다. 인자로 true / false, option을 받을 수 있습니다.

option으로 block, inline, behavior이 있습니다.

block : start / end [ 수직 요소에 대한 옵션 ]

inline : start / left / center / nearest [ 수평 요소에 대한 옵션 ]

behavior : auto / smooth [ 스크롤시 움직임에 대한 옵션 ]

반응형

+ Recent posts