Output
install one package react icons
npm i react-icons
ScrollToTop.js Code
import React, { useEffect, useState } from "react";
import { FaAngleUp } from "react-icons/fa";
import "./ScrollToTop.css";
const ScrollToTop = () => {
const [showTopBtn, setShowTopBtn] = useState(false);
useEffect(() => {
window.addEventListener("scroll", () => {
if (window.scrollY > 400) {
setShowTopBtn(true);
} else {
setShowTopBtn(false);
}
});
}, []);
const goToTop = () => {
window.scrollTo({
top: 0,
behavior: "smooth",
});
};
return (
<>
<div className="top-to-btn">
{" "}
{showTopBtn && (
<FaAngleUp className="icon-position icon-style" onClick={goToTop} />
)}{" "}
</div>
</>
);
};
export default ScrollToTop;
ScrollToTop.css Code
.top-to-btn{
position: relative;
}
.icon-position{
position: fixed;
bottom: 40px;
right: 25px;
z-index: 20;
}
.icon-style{
background-color: #551B54;
border: 2px solid #fff;
border-radius: 50%;
height: 50px;
width: 50px;
color: #fff;
cursor: pointer;
animation: movebtn 3s ease-in-out infinite;
transition: all .5s ease-in-out;
}
.icon-style:hover{
animation: none;
background: #fff;
color: #551B54;
border: 2px solid #551B54;
}
@keyframes movebtn {
0%{
transform: translateY(0px);
}
25%{
transform: translateY(20px);
}
50%{
transform: translateY(0px);
}
75%{
transform: translateY(-20px);
}
100%{
transform: translateY(0px);
}
}
.modal {
font-size: 12px;
}
.modal > .header {
width: 100%;
border-bottom: 1px solid gray;
font-size: 18px;
text-align: center;
padding: 5px;
}
.modal > .content {
width: 100%;
padding: 10px 5px;
}
.modal > .actions {
width: 100%;
padding: 10px 5px;
margin: auto;
text-align: center;
}
.modal > .close {
cursor: pointer;
position: absolute;
display: block;
padding: 2px 5px;
line-height: 20px;
right: -10px;
top: -10px;
font-size: 24px;
background: #ffffff;
border-radius: 18px;
border: 1px solid #cfcece;
}
Originally published
https://democoding.netlify.app/post/how-to-create-a-scroll-to-top-button-in-react
For more information
Subscribe my Youtube Channel
https://www.youtube.com/@democodeCheck out my Fiver profile if you need any freelancing work
https://www.fiverr.com/amit_sharma77Follow me on Instagram
https://www.instagram.com/fromgoodthings/Check out my Facebook Page
Programming memes by CoderLinktree
https://linktr.ee/jonSnow77
Top comments (0)