Created
November 6, 2020 16:38
-
-
Save chadrehm/234f6f1fd936a23d3c292402176b0295 to your computer and use it in GitHub Desktop.
ScrollToTopArrow
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export const ScrollTopArrowComponent = () => { | |
| // Track whether the scroll arrow is needed. | |
| const [showScroll, setShowScroll] = useState(null); | |
| // Check the scroll state, re-memoize when scroll state changes. | |
| const checkScrollTop = useCallback( | |
| () => { | |
| const headerHeight = 400; | |
| if (!showScroll && window.pageYOffset > headerHeight) { | |
| setShowScroll(true); | |
| } else if (showScroll && window.pageYOffset <= headerHeight) { | |
| setShowScroll(false); | |
| } | |
| }, | |
| [showScroll], | |
| ); | |
| // Add/remove the event listener when the component is unmounted or the scroll state has changed. | |
| useEffect( | |
| () => { | |
| window.addEventListener('scroll', checkScrollTop); | |
| return () => window.removeEventListener('scroll', checkScrollTop); | |
| }, | |
| [checkScrollTop], | |
| ); | |
| const scrollTop = () => { | |
| window.scrollTo({ top: 0, behavior: 'smooth' }); | |
| }; | |
| return ( | |
| <div className="scrollTop"> | |
| <button | |
| onClick={scrollTop} | |
| style={{ display: showScroll ? 'flex' : 'none' }} | |
| > | |
| <span className="fa fa-chevron-up" /> | |
| </button> | |
| </div> | |
| ); | |
| }; |
Author
Matthew Croak wrote a great article. Just needed a quick edit.
FYI: This snippet was part of a production code base. It was edited for the gist and has not been tested.
It seems to work fine. Thank you.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Matthew Croak wrote a great article. Just needed a quick edit.
FYI: This snippet was part of a production code base. It was edited for the gist and has not been tested.