ui icon indicating copy to clipboard operation
ui copied to clipboard

[feat]: Is there BackTop Button?

Open ravenkim opened this issue 1 year ago • 2 comments
trafficstars

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

  • [X] I've made research efforts and searched the documentation
  • [X] I've searched for existing issues and PRs

ravenkim avatar Jun 20 '24 02:06 ravenkim

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>
  )
}

bismitpanda avatar Jun 20 '24 12:06 bismitpanda

Thanks!

ravenkim avatar Jun 21 '24 00:06 ravenkim

This issue has been automatically closed because it received no activity for a while. If you think it was closed by accident, please leave a comment. Thank you.

shadcn avatar Jul 14 '24 23:07 shadcn