FrontEnd
[React] ref를 활용하여 스크롤 조절하기
mingg123
2021. 10. 28. 22:01
버튼을 누르면서 한 페이지에서 화면을 전환하는게 필요했다.
라이브러리가 많았지만 기존에 제공하는 window.scrollTo를 사용해서 짰다.
const scrollToRef = (ref: any) => window.scrollTo(0, ref.current.offsetTop);
// General scroll to element function
const App = () => {
const myRef = useRef(null);
const myRef2 = useRef(null);
const executeScroll = () => scrollToRef(myRef);
const executeScrollDown = () => scrollToRef(myRef2);
return (
<>
<div style={{ height: 300, overflow: "auto" }}>
<button onClick={executeScrollDown}> Click to down </button>
<div style={{ height: 100 }} ref={myRef}>
I wanna be seen
</div>
<button onClick={executeScroll} ref={myRef2}>
Click to scroll{" "}
</button>
</div>
</>
);
};
export default App;