Open ravenkim opened 2 weeks ago
You can use this as a component for scroll to top
import { Button, ButtonProps } from "@/components/ui/button";
import { useEffect, useState } from "react";
export function ScrollToTop({
minHeight, // Height from which button will be visible
scrollTo, // Height to go on scroll to top
...props
}: ButtonProps & { minHeight?: number; scrollTo?: number }) {
const [visible, setVisible] = useState(false);
useEffect(() => {
const onScroll = () => {
setVisible(document.documentElement.scrollTop >= (minHeight ?? 0));
};
onScroll();
document.addEventListener("scroll", onScroll);
return () => document.removeEventListener("scroll", onScroll);
}, []);
return (
<>
{visible && (
<Button
onClick={() =>
window.scrollTo({
top: scrollTo ?? 0,
behavior: "smooth",
})
}
{...props}
/>
)}
</>
);
}
and use it as something like
import { ScrollToTop } from "@/components/scroll-to-top";
import { ArrowUpToLine } from "lucide-react";
export default Page() {
return (
<div className="relative">
{/* Some content */}
<ScrollToTop minHeight={20} scrollTo={10} className="absolute right-4 bottom-4">
<ArrowUpToLine />
</ScrollToTop>
</div>
)
}
Thanks!
Feature description
I want BackTop position fixed and when I click it goes to top
Affected component/components
Button
Additional Context
Additional details here...
Before submitting