Reputation: 1
The scroll to the top button is not showing after the scroll reaches 300 pixels. The scroll event is not triggering. I think the problem is maybe with react router Dom v6, because, when I apply the same code in other projects without a React router, the code works. When I manually change the state to true, the button shows, but has no functionality. I'm using "react": "^18.2.0", "react-dom": "^18.2.0", "react-router": "^6.3.0", "react-router-dom": "^6.3.0". This is my first React project, so I'm new to this. I would really appreciate it if someone could please help me with this. This is my code:
import { useEffect, useState } from "react";
import { BiArrowFromBottom } from "react-icons/bi";
import "./scrollToTop.scss";
const ScrollToTop = () => {
const [isVisible, setIsVisible] = useState(false);
const toggleVisibility = () => {
if (window.pageYOffset > 300) {
setIsVisible(true);
} else {
setIsVisible(false);
}
};
const scrollToTop = () => {
window.scrollTo({
top: 0,
behavior: "smooth",
});
};
useEffect(() => {
window.addEventListener("scroll", toggleVisibility);
return () => {
window.removeEventListener("scroll", toggleVisibility);
};
}, []);
return (
<div className="top-to-btm">
{isVisible && (
<BiArrowFromBottom
onClick={scrollToTop}
className="icon-position icon-style"
/>
)}
</div>
);
};
export default ScrollToTop;
import ScrollToTop from "./components/backtotop/scrollToTop";
import { BrowserRouter } from "react-router-dom";
const App = () => {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
</Routes>
<ScrollToTop />
</BrowserRouter>
);
};
export default App;
.top-to-btm {
position: relative;
}
.icon-position{
position: fixed;
bottom: 40px;
right: 35px;
z-index: 20;
}
.icon-style{
background-color: #725034;
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: #725034;
border: 2px solid #725034;
}
@keyframes movebtn {
0%{
transform: translateY(0px);
}
25%{
transform: translateY(20px);
}
50%{
transform: translateY(0px);
}
75%{
transform: translateY(-20px);
}
100%{
transform: translateY(0px);
}
}
Upvotes: 0
Views: 384