import React, { useEffect, useState } from "react"; import { DownArrowIcon } from "./Icons"; const BackToTop = () => { const [scrollPosition, setScrollPosition] = useState(0); // SCROLL TO TOP FUNCTION WHEN CLICK ON THIS PAGE SCROLL TOP function scrollToTop() { window.scrollTo({ top: 0, behavior: "smooth", }); } // TO FIND SCROLL Y POSITION const handleScroll = () => { const position = window.pageYOffset; setScrollPosition(position); }; // THIS USEFFECT GIVE US POSITION OF SCROLL IN EVERY PIXELS WE SCROLL useEffect(() => { window.addEventListener("scroll", handleScroll, { passive: true }); return () => { window.removeEventListener("scroll", handleScroll); }; }, []); return ( <> {/* // IF PAGE SCROLL VALUE GRATER THAN 500 THEN SHOW BACK TO TOP BUTTON */} {scrollPosition > 300 && ( <div className="back-to-top " onClick={() => scrollToTop()}> <DownArrowIcon /> </div> )} </> ); }; export default BackToTop; export const DownArrowIcon = () => { return ( <> <svg width="25" height="10" viewBox="0 0 28 16" fill="none" xmlns="http://www.w3.org/2000/svg" > <path d="M1 1L14 14L27 1" stroke="#1EADB6" strokeWidth="5" /> </svg> </> ); }; // BACKTOP TOP STYLE ADD IN CSS FILE // .back-to-top { // position: fixed; // bottom: 20px; // right: 20px; // z-index: 999; // background: #18c7f4; // border-radius: 50%; // width: 45px; // height: 45px; // display: -webkit-box; // display: -ms-flexbox; // display: flex; // -webkit-box-pack: center; // -ms-flex-pack: center; // justify-content: center; // -webkit-box-align: center; // -ms-flex-align: center; // align-items: center; // cursor: pointer; // -webkit-transition: all 0.3s ease-in-out; // -o-transition: all 0.3s ease-in-out; // transition: all 0.3s ease-in-out; // -webkit-animation: updown-element-animation 2s infinite; // animation: updown-element-animation 2s infinite; // }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter