Ads by ProfitSence
Close

Scroll to Top Button Component for your Gatsby Site

Last Updated on Wednesday 5th Oct 2022
  • The Event Listener and Hook
  • The useEffect hook gets called when the component is mounted.
  • That's the perfect place to instantiate an event listener for the window scroll event.
			
					import React, { useState, useEffect } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faArrowCircleUp } from "@fortawesome/free-solid-svg-icons";

const ScrollTopBtn = () => {
  const [showScroll, setShowScroll] = useState(false);

  useEffect(function setUpListener() {
    const updateState = () => {
      let scrollY = window.pageYOffset;

      if (!showScroll && scrollY > 400) {
        setShowScroll(true);
      } else if (showScroll && scrollY <= 400) {
        setShowScroll(false);
      }
    };
    window.addEventListener("scroll", updateState);

    return function cleanUpListener() {
      window.removeEventListener("scroll", updateState);
    };
  });

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

  return (
    <div>
      <div
        id="scroll"
        onClick={scrollTop}
        onKeyDown={scrollTop}
        role="link"
        aria-label="scroll"
        tabIndex={0}
        style={showScroll === true ? { display: "block" } : { display: "none" }}
      >
        <FontAwesomeIcon id="arrowUp" icon={faArrowCircleUp} />
      </div>
    </div>
  );
};
export default ScrollTopBtn;

			
	
			
					#scroll {
  position: fixed;
  bottom: 20px;
  right: 30px;
  z-index: 99;
}
#arrowUp {
  cursor: pointer;
  font-size: 2rem;
  border-radius: 50%;
  opacity: 0.5;
}
#arrowUp:hover {
  color: #52bc77;
  font-size: 2.2rem;
  opacity: 1;
}