shadcn-ui / ui

Beautifully designed components that you can copy and paste into your apps. Accessible. Customizable. Open Source.
https://ui.shadcn.com
MIT License
63.94k stars 3.62k forks source link

[feat]: Is there BackTop Button? #4048

Open ravenkim opened 2 weeks ago

ravenkim commented 2 weeks ago

Feature description

image

I want BackTop position fixed and when I click it goes to top

Affected component/components

Button

Additional Context

Additional details here...

Before submitting

blood-rogue commented 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>
  )
}
ravenkim commented 2 weeks ago

Thanks!