Skip to content

Instantly share code, notes, and snippets.

@carpben
Last active June 8, 2019 01:38
Show Gist options
  • Save carpben/f8d1708b8670bda00e54941d62231ef4 to your computer and use it in GitHub Desktop.
Save carpben/f8d1708b8670bda00e54941d62231ef4 to your computer and use it in GitHub Desktop.
const scrollToRef = (ref) => window.scrollTo(0, ref.current.offsetTop) // General scroll to element function
const ReadyToScroll = () => {
const myRef = useRef(null) // Hook to ref object
return (<div ref={myRef}>I wanna be seen</div>) // Attach ref object to a dom element
}
// To scroll run `scrollToRef(myRef)`. Examples:
// To scroll on mount add above the return statement:
useEffect(() => {
scrollToRef(myRef)
}, [])
// To scroll on click change the return statement:
return (
<>
<div ref={myRef}>I wanna be seen</div>
<button onClick={()=>scrollToRef(myRef)} > Scroll from me </button>
</>
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment