16
loading...
This website collects cookies to deliver better user experience
const topRef = useRef(null);
ref
attribute:<div className="App">
<h1 ref={topRef}>Scroll To Top Example</h1>
</div>
scrollToRef
function to its click event. This function takes will accept the target ref, and use the scrollTo()
function on the window
object to scroll the window until the top of the ref
element is visible. To make this action smooth, instead of an instantaneous jump, we can optionally pass a "behavior" property:const scrollToRef = (target) => {
window.scrollTo({
top: target.current.offsetTop,
behavior: "smooth"
});
}
scrollY
property on the window
object to determine how far down the page the user has scroll. With an event listener on the scroll event for the window, we can then compare the scrollY position of the window at each scroll to determine if the button's "show" state should be true or false. Alternatively, we could make this comparison on scroll start or scroll end to improve performance, but it would change its behavior.useEffect
hook that will be invoked when the component un-mounts.const GoToButton = ({ displayAfter, target }) => {
const [showButton, setShowButton] = useState(false);
const handleShowButton = () => {
if (!showButton && window.scrollY > displayAfter) {
setShowButton(true);
return;
}
if (!showButton && window.scrollY <= displayAfter) {
setShowButton(false);
return;
}
};
window.addEventListener("scroll", handleShowButton);
useEffect(() => {
return window.removeEventListener("scroll", handleShowButton);
});
const scrollToRef = (target) => {
window.scrollTo({
top: target.current.offsetTop,
behavior: "smooth"
});
};
if (showButton) {
return <Button onClick={() => scrollToRef(target)}>TOP</Button>;
} else {
return "";
}
};
export default GoToButton;
scrollBy
method which could be used in place of scrollTo if the desired behavior was to always scroll a specific distance, such as using window.scrollBy(0, window.innerHeight)
to scroll down by one page.