| 1 | import React, { useState, useEffect } from 'react'; |
| 2 | |
| 3 | function useScrollPosition() { |
| 4 | const [percent, setPercent] = useState(0); |
| 5 | |
| 6 | function handleScroll(event) { |
| 7 | const scrollTop = |
| 8 | document.scrollingElement.scrollHeight - |
| 9 | document.documentElement.clientHeight; |
| 10 | const howFar = document.documentElement.scrollTop / scrollTop; |
| 11 | setPercent(howFar); |
| 12 | } |
| 13 | |
| 14 | useEffect(() => { |
| 15 | // listen for window scroll event |
| 16 | document.addEventListener('scroll', handleScroll); |
| 17 | return () => { |
| 18 | document.removeEventListener('scroll', handleScroll); |
| 19 | }; |
| 20 | }); |
| 21 | |
| 22 | return percent; |
| 23 | } |
| 24 | |
| 25 | export default function BackToTop() { |
| 26 | const percent = useScrollPosition(); |