1import React, { useRef } from 'react'
2
3const scrollToRef = (ref) => window.scrollTo(0, ref.current.offsetTop)
4// General scroll to element function
5
6const ScrollDemo = () => {
7
8 const myRef = useRef(null)
9 const executeScroll = () => scrollToRef(myRef)
10
11 return (
12 <>
13 <div ref={myRef}>I wanna be seen</div>
14 <button onClick={executeScroll}> Click to scroll </button>
15 </>
16 )
17}
18
1class ReadyToScroll extends Component {
2
3 constructor(props) {
4 super(props)
5 this.myRef = React.createRef()
6 }
7
8 render() {
9 return <div ref={this.myRef}></div>
10 }
11
12 scrollToMyRef = () => window.scrollTo(0, this.myRef.current.offsetTop)
13 // run this method to execute scrolling.
14
15}