button scroll element to top react code example
Example 1: scroll to top in react
componentDidMount() {
window.scrollTo(0, 0)
}
Example 2: react how to scroll to element
import React, { useRef } from 'react'
const scrollToRef = (ref) => window.scrollTo(0, ref.current.offsetTop)
// General scroll to element function
const ScrollDemo = () => {
const myRef = useRef(null)
const executeScroll = () => scrollToRef(myRef)
return (
<>
<div ref={myRef}>I wanna be seen</div>
<button onClick={executeScroll}> Click to scroll </button>
</>
)
}