GoToTop.tsx 801 B

12345678910111213141516171819202122232425262728293031323334353637
  1. import clsx from 'clsx';
  2. import Icon from '@/components/Icon';
  3. import { useEffect, useState } from 'react';
  4. export default function GoToTop() {
  5. const [goToTopVisible, setGoToTopVisible] = useState(false);
  6. const pop = () => {
  7. setGoToTopVisible(window.pageYOffset > window.innerHeight / 2);
  8. };
  9. const scrollToTop = e => {
  10. window.scroll({
  11. top: 0,
  12. behavior: 'smooth'
  13. });
  14. e.preventDefault();
  15. return false;
  16. };
  17. useEffect(() => {
  18. window.addEventListener('scroll', pop);
  19. return () => window.removeEventListener('scroll', pop);
  20. }, []);
  21. return (
  22. <button
  23. className={clsx('go-to-top', goToTopVisible && 'go-to-top-visible')}
  24. aria-label="Go to top"
  25. onClick={scrollToTop}
  26. >
  27. <Icon name="chevron-up" />
  28. </button>
  29. );
  30. }