How to create scroll to top button in react
When we visit any website which has a lot of content. We scroll down to read it. Then we see a back to top button which will help me to got at the top in the website. It's feel goood to see that functionality. Think if not have back to top button. Visitors experience will be not good. And back to top button will be visible when you scrolled down some distance.
So in this post, we are creating backc to top button from scratch without using any third-party libraries.
We will use useState hook, useEffect hook, and window object.
To smoothly scroll the window to the top, we use:
window.scrollTo({ top:0, left:0, behavior:"smooth" });
We create a function to listenToScroll
const listenToScroll = () =>{ let heightToHidden = 250; const winScroll = document.body.scrollTop || document.documentElement.scrollTop; if(winScroll > heightToHidden){ setIsVisible(true) } else { setIsVisible(false); } }
We will se useEffect Hooks to listen scroll by user and will handle by listenToScroll function.
useEffect(() => { window.addEventListener("scroll",listenToScroll); return () => { window.removeEventListener("scroll",listenToScroll); } },[])
this is css code for back to top button
.go_to_top { right:20px; bottom: 20px; position: fixed; background-color: #012970; height: 40px; width:40px; display: flex; justify-content: center; align-items: center; color: #fff; font-size: 18px; border-radius: 50%; cursor: pointer; z-index: 999; } .go_to_top i{ animation: goto 1.2s linear infinite alternate-reverse; } @keyframes goto { 0%{ transform: translateY(-5px); } 100%{ transform: translateY(5px); } }
We are creating a new Component with GoToTop.js
import {useState,useEffect} from 'react' import '../index.css' const GoToTop = () => { const [isVisible, setIsVisible] = useState(false); const listenToScroll = () =>{ let heightToHidden = 250; const winScroll = document.body.scrollTop || document.documentElement.scrollTop; if(winScroll > heightToHidden){ setIsVisible(true) } else { setIsVisible(false); } } useEffect(() => { window.addEventListener("scroll",listenToScroll); return () => { window.removeEventListener("scroll",listenToScroll); } },[]) const goToBtn = () =>{ window.scrollTo({ top:0, left:0, behavior:"smooth" }); } return ( <> { isVisible && ( <div className='go_to_top' onClick={goToBtn}> <i className='fa fa-arrow-up'></i> </div> ) } </> ) } export default GoToTop
Now import this component in your App Component and use it.