We are going to create a React button component that when clicked, the page smoothly scrolls back to the top.

Here is the simple concept to create this in React.

The scroll to top button is positioned at the bottom-right of the screen and hidden by default When we scroll to a specific viewport, the button is visible When the user clicks the button, it scrolls back to the top of the page

Easy. Huh?

Before we dive in, here is the working example.

Yeah. Let's set-up our component -

import React, { Component } from "react"; export default class ScrollToTop extends Component { constructor(props) { } componentDidMount() { } toggleVisibility() { } scrollToTop() { } render() { return ( <div className="scroll-to-top"> <div> </div> </div> ); } }

We are going to use a React lifecycle method componentDidMount() with few the other methods to achieve this.

Here are the steps to create our scroll to top button React component -

Step 1: constructor()

A method that is fired before the component is mounted, that handles our initial setup. This is the first thing that gets called. Here, we set the visibility state of our button to false.

constructor(props) { super(props); this.state = { is_visible: false }; }

Step 2: componentDidMount()

A lifecycle method that is invoked after our component is rendered for the first time.

componentDidMount() { var scrollComponent = this; document.addEventListener("scroll", function(e) { scrollComponent.toggleVisibility(); }); }

Step 3: toggleVisibility()

This method checks the scroll position and updates the state. When the page is scroll to the specific position, say 300px the visibility state of our button changed to true.

toggleVisibility() { if (window.pageYOffset > 300) { this.setState({ is_visible: true }); } else { this.setState({ is_visible: false }); } }

Step 4: scrollToTop()

And, this method just scrolls the page back to the top smoothly.

scrollToTop() { window.scrollTo({ top: 0, behavior: "smooth" }); }

Step 5: Render()

Finally, we need to apply all that to our button element to render. I have used SVG icon button for this.

. . . render() { const { is_visible } = this.state; return ( <div className="scroll-to-top"> {is_visible && ( <div onClick={() => this.scrollToTop()}> <svg xmlns="http://www.w3.org/2000/svg" height="38.735" width="33.749" > <g transform="translate(-18.121 -3.364)"> <rect ry="4.928" y="3.364" x="18.121" height="38.735" width="33.749" fill="#00f" /> <g transform="translate(-.48 2.134)"> <rect ry="4.928" y="1.229" x="18.601" height="38.735" width="33.749" fill="url(#b)" /> <g fill="#ececec"> <path d="M22.435 17.62l4.684 4.685 5.044-5.044v19.352h6.625V17.26l5.044 5.044 4.683-4.684-13.04-13.04z" /> <path d="M22.435 17.62l4.684 4.685 5.044-5.044v19.352h6.625V17.26l5.044 5.044 4.683-4.684-13.04-13.04z" /> </g> </g> </g> </svg> </div> )} </div> ); } } . . .

Easy as pie. Now import this component globally in header or footer component.