2
\$\begingroup\$

Pretty new to React/Next.js. This is for a "back to top" button. Any thoughts on whether this can be improved? I haven't really got my head around when useEffect should be used, for example, but what I've written is running fine.

import React, { useEffect } from 'react';
import Chevron from '@/components/Icons/Chevron';

export default function BackToTop() {

  const scrollToTop = () => {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }

  useEffect(() => {

    let scrollPosition = 0;

    const isScrollingDown = () => {      
      let scrollingDown = false;
      let newScrollPosition = window.pageYOffset;
      if (newScrollPosition > scrollPosition) {
        scrollingDown = true;
      }
      scrollPosition = newScrollPosition;
      return scrollingDown;
    };
    
    const handleScroll = () => {
      const scrollToTopButton = document.querySelector('[data-backToTopButton]');
      if (isScrollingDown() || window.pageYOffset == 0) {
        scrollToTopButton.classList.add('opacity-0', 'invisible');
        scrollToTopButton.classList.remove('opacity-100', 'visible');
      } else {
        scrollToTopButton.classList.remove('opacity-0', 'invisible');
        scrollToTopButton.classList.add('opacity-100', 'visible');
      }
    };
    
    window.addEventListener("scroll", handleScroll);

  });

  return (
    <div data-backToTopButton role="button" onClick={scrollToTop} aria-label="Back to top" title="Back to top" className="fixed bottom-4 right-2 z-10 bg-[#9147FF] text-white group w-[60px] h-[60px] rounded-full flex items-center justify-center shadow-back-to-top opacity-0 invisible">
      <Chevron width="30" height="20" extraClasses="transition-all duration-500 relative top-0 group-hover:-top-0.5 -mt-1" /> 
    </div>
  )

}
\$\endgroup\$
1
  • \$\begingroup\$ Title should explain what the code is doing, hope I understood it right. \$\endgroup\$ Commented Feb 27, 2023 at 14:22

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.