- 이동하고 싶은 dom 에다 ref 선언
- scrollIntoView 속성 이용
- {behavior: 'smooth'} 옵션을 주면 부드럽게 스크롤이 이동
function TestComponent() {
const myRef = React.useRef(null);
const scrollToElement = () => myRef.current.scrollIntoView({ behavior: 'smooth' });
return (
<>
<div ref={myRef}>Element you want to view</div>
<button onClick={scrollToElement}>Trigger the scroll</button>
</>
);
}
class TestComponent extends Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
scrollToElement = () => {
myRef.current.scrollIntoView({ behavior: 'smooth' });
};
return (
<>
<div ref={myRef}>Element you want to view</div>
<button onClick={this.scrollToElement}>Trigger the scroll</button>
</>
)
}