Skip to content

Instantly share code, notes, and snippets.

@chadrehm
Created November 6, 2020 16:38
Show Gist options
  • Select an option

  • Save chadrehm/234f6f1fd936a23d3c292402176b0295 to your computer and use it in GitHub Desktop.

Select an option

Save chadrehm/234f6f1fd936a23d3c292402176b0295 to your computer and use it in GitHub Desktop.
ScrollToTopArrow
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>
);
};
@chadrehm
Copy link
Author

chadrehm commented Nov 6, 2020

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.

@karvas
Copy link

karvas commented Nov 7, 2020

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