How To Create a React Scroll To Top Button?
Create a React scroll top button that will take the user to the top of the page when clicked on.
The scroll to top button is positioned at the bottom right of the screen and by default hidden.
When user scroll top of the page the button will be showing.
Step 1:
Create a component GoTop.js
import React, { Component } from "react";
export default class GoTop extends Component {
constructor(props) {
super(props);
this.state = {
is_visible: false
};
}
componentDidMount() {
var scrollComponent = this;
document.addEventListener("scroll", function(e) {
scrollComponent.toggleVisibility();
});
}
toggleVisibility() {
if (window.pageYOffset > 300) {
this.setState({
is_visible: true
});
} else {
this.setState({
is_visible: false
});
}
}
scrollToTop() {
window.scrollTo({
top: 0,
behavior: "smooth"
});
}
render() {
const { is_visible } = this.state;
return (
<div className="back-to-top show-back-to-top">
{is_visible && (
<div className="top" onClick={() => this.scrollToTop()}>
Top
</div>
)}
</div>
);
}
}
Step 2:
Add the CSS in the style.css
.back-to-top .top {
position: fixed;
cursor: pointer;
bottom: 15px;
right: 15px;
font-size: 25px;
color: #ffffff;
background-color: #000000;
z-index: 4;
width: 45px;
text-align: center;
height: 45px;
line-height: 45px;
border-radius: 50%;
-webkit-transition: 0.5s;
transition: 0.5s;
}
.back-to-top .top:hover {
color: #ffffff;
background: #ff3366;
}