SunUI
創設メンバー$79・永久更新・1月11日まで枠を確保する
無料スクロール

トップへ戻る

しきい値を越えてスクロールすると現れる丸いボタン。

使いどころ

  • 長いカテゴリページ、検索結果、記事

注意点

  • 同じ角のチャットボタンや Cookie バナーと重ならないように
  • ページに scroll-progress があるなら showProgress をオフに

エージェントに追加してもらう

インストールコマンド、使いどころ、props、デザインルールを一度にコピーできます。Claude Code、Cursor、Codex に貼り付けてください。

CLI でインストール

shadcn CLI を使います。ソースはプロジェクトにコピーされるので、すべての行があなたのものです。

$ npx shadcn@latest add https://sunui.synvize.com/r/back-to-top.json

手動でインストール

  1. 1. 依存パッケージをインストールします。
    $ npm install clsx tailwind-merge framer-motion
  2. 2. cn ヘルパーがなければ lib/utils.ts に追加します。shadcn/ui を使っていない場合は、色のトークン用に sunui-theme.css も追加します(手順)。そのあとコンポーネントをコピーします。
    back-to-top.tsx
    "use client";
    
    import { AnimatePresence, motion, useMotionValueEvent, useReducedMotion, useScroll } from "framer-motion";
    import { useState, type RefObject } from "react";
    
    import { cn } from "@/lib/utils";
    
    const springs = {
      snappy: { type: "spring", stiffness: 520, damping: 34 },
      gentle: { type: "spring", stiffness: 240, damping: 30 },
    } as const;
    
    export interface BackToTopProps {
      /** Pass this when used inside a scrollable container. Defaults to the window */
      container?: RefObject<HTMLElement | null>;
      /** How many px must be scrolled before it appears */
      threshold?: number;
      /** Shows reading progress on the outer ring */
      showProgress?: boolean;
      /** fixed: pinned to a window corner. contained: pinned to the corner of the nearest relative container (for a scrollable container, wrap it in sticky) */
      position?: "fixed" | "contained";
      label?: string;
      className?: string;
    }
    
    /** Brand accent color: follows the theme's --primary by default, and buyers can set --sunui-spot to use their own brand color. Used only for selected, deal and current-progress states */
    const spot = "text-[color:var(--sunui-spot,var(--primary))]";
    
    const R = 21;
    const C = 2 * Math.PI * R;
    
    export function BackToTop({ container, threshold = 400, showProgress = true, position = "fixed", label = "Back to top", className }: BackToTopProps) {
      const reduce = useReducedMotion();
      const { scrollY, scrollYProgress } = useScroll(container ? { container, ...{ layoutEffect: false } } : undefined);
      const [shown, setShown] = useState(false);
      const [progress, setProgress] = useState(0);
    
      useMotionValueEvent(scrollY, "change", (y) => setShown(y > threshold));
      useMotionValueEvent(scrollYProgress, "change", (p) => setProgress(p));
    
      const toTop = () => {
        const target = container?.current ?? window;
        target.scrollTo({ top: 0, behavior: reduce ? "auto" : "smooth" });
      };
    
      return (
        <AnimatePresence>
          {shown && (
            <motion.button
              type="button"
              aria-label={label}
              onClick={toTop}
              initial={reduce ? { opacity: 0 } : { opacity: 0, y: 16 }}
              animate={{ opacity: 1, y: 0, transition: reduce ? { duration: 0 } : springs.gentle }}
              exit={reduce ? { opacity: 0, transition: { duration: 0 } } : { opacity: 0, y: 16, transition: { duration: 0.15 } }}
              whileTap={reduce ? undefined : { scale: 0.94, transition: springs.snappy }}
              className={cn(
                "z-40 grid size-12 place-items-center rounded-full border border-foreground/10 bg-card text-foreground outline-offset-2 focus-visible:outline-2 shadow-[0_1px_2px_rgb(0_0_0/0.05)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]",
                position === "fixed" ? "fixed bottom-6 right-6" : "absolute bottom-4 right-4",
                className,
              )}
            >
              {showProgress && (
                <svg viewBox="0 0 48 48" className="absolute inset-0 size-full -rotate-90" aria-hidden="true">
                  <circle cx="24" cy="24" r={R} className={spot} fill="none" stroke="currentColor" strokeWidth="1.5" strokeDasharray={C} strokeDashoffset={C * (1 - progress)} strokeLinecap="round" />
                </svg>
              )}
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="relative size-5" aria-hidden="true">
                <path d="M12 19V5M6 11l6-6 6 6" />
              </svg>
            </motion.button>
          )}
        </AnimatePresence>
      );
    }