I'm really new to React and I've been trying for some time now to make a scroll to top function. Using the existing tutorials and everything on google i've made this component :
Import React, { useState, useEffect } from "react";
export default function 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);
};
}, []);
if (!isVisible) {
return false
}
return (
<button className="button" onClick={ScrollToTop}>
<div className="button__arrow button__arrow--up"></div>
</button>
)
};
the problem is that when i import it in the App.js it doesn't work properly, the scrolling part works perfectly, but the button it just stays at bottom of the page instead of appearing after a certain amount of scroll. This is the App.js:
return (
<div>
{loading ? (
<h1>Loading...</h1>
) : (
<>
<Navbar />
<div className="Grid-container">
{pokemonData.map((pokemon, i) => {
return <Card key={i} pokemon={pokemon} />;
})}
</div>
<ScrollToTop/>
</>
)}
</div>
);
}