Add Scroll To Top In Pure Javascript & React.Js

How to add scroll to top in pure Javascript & React.js

How to add scroll to top in pure Javascript & React.js

Create scroll to top in webpage while you are in the bottom or middle of a webpage, you can find many react packages for that but I want to share that using custom functionalities, so let’s dive into that.

First of all, create a component like GoTop or GoToTop or ScrollUp or anything whatever you think that’s doesn’t matter actually, and I am creating a component which name is GoTop like below

class GoTop extends React.Component {
    state = {
         intervalId: 0,
         thePosition: false
    componentDidMount() { 
       document.addEventListener("scroll", () => { 
           if (window.scrollY > 170) { 
                this.setState({ thePosition: true }) 
           } else { 
               this.setState({ thePosition: false }) 
        window.scrollTo(0, 0); 
    onScrollStep = () => { 
        if (window.pageYOffset === 0){ 
       window.scroll(0, window.pageYOffset - this.props.scrollStepInPx); 
    scrollToTop = () => { 
       let intervalId = setInterval(this.onScrollStep, this.props.delayInMs); 
       this.setState({ intervalId: intervalId }); 
    renderGoTopIcon = () => { 
        if (this.state.thePosition){ 
           return Go Top
        return ( {this.renderGoTopIcon()} ) 

Now you can just render this component in where you need like this below

That’s it.

You can see this example in codepent see the below

See the Pen
React Go To Top
by Shabbir Ahmed (@shabblr_ahmed)
on CodePen.





Leave a Reply

Your email address will not be published. Required fields are marked *