~/components/back-to-top
Back to Top
A small square button that appears after the first screen and scrolls back up, with a reduced-motion jump and optional focus target.
$ make build # scroll down
[01] build step 1 ok
[02] build step 2 ok
[03] build step 3 ok
[04] build step 4 ok
[05] build step 5 ok
[06] build step 6 ok
[07] build step 7 ok
[08] build step 8 ok
[09] build step 9 ok
[10] build step 10 ok
[11] build step 11 ok
[12] build step 12 ok
[13] build step 13 ok
[14] build step 14 ok
[15] build step 15 ok
[16] build step 16 ok
[17] build step 17 ok
[18] build step 18 ok
[19] build step 19 ok
[20] build step 20 ok
[21] build step 21 ok
[22] build step 22 ok
[23] build step 23 ok
[24] build step 24 ok
[25] build step 25 ok
[26] build step 26 ok
[27] build step 27 ok
[28] build step 28 ok
[29] build step 29 ok
[30] build step 30 ok
[31] build step 31 ok
[32] build step 32 ok
[33] build step 33 ok
[34] build step 34 ok
[35] build step 35 ok
[36] build step 36 ok
[37] build step 37 ok
[38] build step 38 ok
[39] build step 39 ok
[40] build step 40 ok
"use client";
import { useEffect, useRef, useState, type ReactNode, type RefObject } from "react";
export type BackToTopProps = {
/** Scroll container to watch and scroll. Leave empty to use the page. @default undefined (the window) */
target?: RefObject<HTMLElement | null>;
/** Pin the button to the bottom-right of the viewport. false places it in the nearest positioned parent instead (use with `target`). @default true */
fixed?: boolean;
/** Show the button after this much scroll: a number below 1 is a share of the visible height, otherwise px. @default 0.8 */
threshold?: number;
/** Accessible name of the button. @default "Back to top" */
label?: string;
/** Element to focus after scrolling up (CSS selector), e.g. "#main" or a skip-link target. Keyboard users then continue from the top. @default undefined */
focusSelector?: string;
/** Scroll smoothly even when the user prefers reduced motion (otherwise it jumps). Use sparingly. @default false */
ignoreReducedMotion?: boolean;
/** Button content. @default "↑" */
children?: ReactNode;
/** Extra classes for the button. */
className?: string;
};
/**
* A small square button that appears once the reader has scrolled down and
* takes them back to the top. While hidden it is `inert`, so it is out of the
* tab order and the accessibility tree. Smooth scrolling falls back to an
* instant jump under reduced motion.
*/
export function BackToTop({
target,
fixed = true,
threshold = 0.8,
label = "Back to top",
focusSelector,
ignoreReducedMotion = false,
children = "↑",
className = "",
}: BackToTopProps) {
const [show, setShow] = useState(false);
const raf = useRef(0);
useEffect(() => {
const el = target?.current ?? null;
const source: HTMLElement | Window = el ?? window;
const update = () => {
raf.current = 0;
const top = el ? el.scrollTop : window.scrollY;
const view = el ? el.clientHeight : window.innerHeight;
setShow(top > (threshold < 1 ? view * threshold : threshold));
};
const schedule = () => {
if (!raf.current) raf.current = requestAnimationFrame(update);
};
schedule();
source.addEventListener("scroll", schedule, { passive: true });
window.addEventListener("resize", schedule);
return () => {
source.removeEventListener("scroll", schedule);
window.removeEventListener("resize", schedule);
cancelAnimationFrame(raf.current);
raf.current = 0;
};
}, [target, threshold]);
const goTop = () => {
const reduced = !ignoreReducedMotion && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const behavior: ScrollBehavior = reduced ? "instant" : "smooth";
(target?.current ?? window).scrollTo({ top: 0, behavior });
if (focusSelector) {
const dest = document.querySelector<HTMLElement>(focusSelector);
if (dest) {
if (!dest.hasAttribute("tabindex") && dest.tabIndex < 0) dest.setAttribute("tabindex", "-1");
dest.focus({ preventScroll: true });
}
}
};
return (
<button
type="button"
onClick={goTop}
aria-label={label}
title={label}
inert={!show}
className={`right-4 bottom-4 z-[60] grid h-9 min-w-9 place-items-center px-2 border border-mpk-line bg-mpk-bg-soft font-mpk-mono text-base text-mpk-blue transition-[opacity,translate,border-color] duration-200 hover:border-mpk-blue focus-visible:border-mpk-blue focus-visible:outline-1 focus-visible:outline-offset-2 focus-visible:outline-mpk-blue motion-reduce:transition-none ${
fixed ? "fixed mb-[env(safe-area-inset-bottom,0px)]" : "absolute"
} ${show ? "translate-y-0 opacity-100" : "pointer-events-none translate-y-2 opacity-0"} ${className}`}
>
{children}
</button>
);
}Installation
npx mpkcn add back-to-top01Add mpkcn-theme.css if you haven't yet (see Installation)
02Copy the source into your components folder
"use client";
import { useEffect, useRef, useState, type ReactNode, type RefObject } from "react";
export type BackToTopProps = {
/** Scroll container to watch and scroll. Leave empty to use the page. @default undefined (the window) */
target?: RefObject<HTMLElement | null>;
/** Pin the button to the bottom-right of the viewport. false places it in the nearest positioned parent instead (use with `target`). @default true */
fixed?: boolean;
/** Show the button after this much scroll: a number below 1 is a share of the visible height, otherwise px. @default 0.8 */
threshold?: number;
/** Accessible name of the button. @default "Back to top" */
label?: string;
/** Element to focus after scrolling up (CSS selector), e.g. "#main" or a skip-link target. Keyboard users then continue from the top. @default undefined */
focusSelector?: string;
/** Scroll smoothly even when the user prefers reduced motion (otherwise it jumps). Use sparingly. @default false */
ignoreReducedMotion?: boolean;
/** Button content. @default "↑" */
children?: ReactNode;
/** Extra classes for the button. */
className?: string;
};
/**
* A small square button that appears once the reader has scrolled down and
* takes them back to the top. While hidden it is `inert`, so it is out of the
* tab order and the accessibility tree. Smooth scrolling falls back to an
* instant jump under reduced motion.
*/
export function BackToTop({
target,
fixed = true,
threshold = 0.8,
label = "Back to top",
focusSelector,
ignoreReducedMotion = false,
children = "↑",
className = "",
}: BackToTopProps) {
const [show, setShow] = useState(false);
const raf = useRef(0);
useEffect(() => {
const el = target?.current ?? null;
const source: HTMLElement | Window = el ?? window;
const update = () => {
raf.current = 0;
const top = el ? el.scrollTop : window.scrollY;
const view = el ? el.clientHeight : window.innerHeight;
setShow(top > (threshold < 1 ? view * threshold : threshold));
};
const schedule = () => {
if (!raf.current) raf.current = requestAnimationFrame(update);
};
schedule();
source.addEventListener("scroll", schedule, { passive: true });
window.addEventListener("resize", schedule);
return () => {
source.removeEventListener("scroll", schedule);
window.removeEventListener("resize", schedule);
cancelAnimationFrame(raf.current);
raf.current = 0;
};
}, [target, threshold]);
const goTop = () => {
const reduced = !ignoreReducedMotion && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const behavior: ScrollBehavior = reduced ? "instant" : "smooth";
(target?.current ?? window).scrollTo({ top: 0, behavior });
if (focusSelector) {
const dest = document.querySelector<HTMLElement>(focusSelector);
if (dest) {
if (!dest.hasAttribute("tabindex") && dest.tabIndex < 0) dest.setAttribute("tabindex", "-1");
dest.focus({ preventScroll: true });
}
}
};
return (
<button
type="button"
onClick={goTop}
aria-label={label}
title={label}
inert={!show}
className={`right-4 bottom-4 z-[60] grid h-9 min-w-9 place-items-center px-2 border border-mpk-line bg-mpk-bg-soft font-mpk-mono text-base text-mpk-blue transition-[opacity,translate,border-color] duration-200 hover:border-mpk-blue focus-visible:border-mpk-blue focus-visible:outline-1 focus-visible:outline-offset-2 focus-visible:outline-mpk-blue motion-reduce:transition-none ${
fixed ? "fixed mb-[env(safe-area-inset-bottom,0px)]" : "absolute"
} ${show ? "translate-y-0 opacity-100" : "pointer-events-none translate-y-2 opacity-0"} ${className}`}
>
{children}
</button>
);
}03Update the import paths to match your project
Usage
Render it once, in your root layout. A small square button fades in at the bottom right after the reader scrolls past most of the first screen.
import { BackToTop } from "@/components/mpkcn/back-to-top";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" suppressHydrationWarning>
<body>
<main id="main">{children}</main>
<BackToTop focusSelector="#main" />
</body>
</html>
);
}Examples
Inside a scroll container
Pass a ref as target and fixed={false} to watch and scroll that element, with the button placed in the nearest positioned parent. Here it shows after 120px.
$ make build # scroll down
[01] build step 1 ok
[02] build step 2 ok
[03] build step 3 ok
[04] build step 4 ok
[05] build step 5 ok
[06] build step 6 ok
[07] build step 7 ok
[08] build step 8 ok
[09] build step 9 ok
[10] build step 10 ok
[11] build step 11 ok
[12] build step 12 ok
[13] build step 13 ok
[14] build step 14 ok
[15] build step 15 ok
[16] build step 16 ok
[17] build step 17 ok
[18] build step 18 ok
[19] build step 19 ok
[20] build step 20 ok
[21] build step 21 ok
[22] build step 22 ok
[23] build step 23 ok
[24] build step 24 ok
[25] build step 25 ok
[26] build step 26 ok
[27] build step 27 ok
[28] build step 28 ok
[29] build step 29 ok
[30] build step 30 ok
[31] build step 31 ok
[32] build step 32 ok
[33] build step 33 ok
[34] build step 34 ok
[35] build step 35 ok
[36] build step 36 ok
[37] build step 37 ok
[38] build step 38 ok
[39] build step 39 ok
[40] build step 40 ok
import { useRef } from "react";
import { BackToTop } from "@/components/mpkcn/back-to-top";
export function BuildLog() {
const ref = useRef<HTMLDivElement>(null);
return (
<div className="relative h-[300px] border border-mpk-line">
<div ref={ref} className="h-full overflow-y-auto p-5">
…
</div>
<BackToTop target={ref} fixed={false} threshold={120} />
</div>
);
}Terminal label
$ make build # scroll down
[01] build step 1 ok
[02] build step 2 ok
[03] build step 3 ok
[04] build step 4 ok
[05] build step 5 ok
[06] build step 6 ok
[07] build step 7 ok
[08] build step 8 ok
[09] build step 9 ok
[10] build step 10 ok
[11] build step 11 ok
[12] build step 12 ok
[13] build step 13 ok
[14] build step 14 ok
[15] build step 15 ok
[16] build step 16 ok
[17] build step 17 ok
[18] build step 18 ok
[19] build step 19 ok
[20] build step 20 ok
[21] build step 21 ok
[22] build step 22 ok
[23] build step 23 ok
[24] build step 24 ok
[25] build step 25 ok
[26] build step 26 ok
[27] build step 27 ok
[28] build step 28 ok
[29] build step 29 ok
[30] build step 30 ok
[31] build step 31 ok
[32] build step 32 ok
[33] build step 33 ok
[34] build step 34 ok
[35] build step 35 ok
[36] build step 36 ok
[37] build step 37 ok
[38] build step 38 ok
[39] build step 39 ok
[40] build step 40 ok
<BackToTop label="Scroll to top">
<span className="text-xs">cd ~</span>
</BackToTop>Props
| Prop | Type | Default | Description |
|---|---|---|---|
| target | RefObject<HTMLElement | null> | window | Scroll container to watch and scroll. Leave empty to use the page. |
| fixed | boolean | true | Pin the button to the bottom right of the viewport. false places it in the nearest positioned parent instead (use with target). |
| threshold | number | 0.8 | Show the button after this much scroll: below 1 is a share of the visible height, otherwise px. |
| label | string | "Back to top" | Accessible name (and tooltip) of the button. |
| focusSelector | string | — | Element to focus after scrolling up, e.g. "#main". Keyboard users then continue from the top. |
| ignoreReducedMotion | boolean | false | Scroll smoothly even when the user prefers reduced motion. Use sparingly. |
| children | ReactNode | "↑" | Button content. |
| className | string | — | Extra classes for the button. |
Accessibility
- It is a real
buttonwith anaria-labeland a visible focus outline. - While hidden it is
inert: out of the tab order and the accessibility tree, so no one tabs onto an invisible control. - Scrolling is smooth by default and jumps instantly under
prefers-reduced-motion: reduce. The fade-in also turns off. - Use
focusSelectorto move keyboard focus to the top of the page after scrolling; otherwise focus would land onbodyonce the button hides. Elements that are not focusable gettabindex="-1"first.