Skip to content
Uxelith
Freev1.0.0Navigation

Bottom Sheet

A sheet that rises from the bottom and rests at the heights you choose: modal for a focused task, or non-modal beside a map or player that stays usable behind it. Scroll hands off to drag, sheets stack, and it rises above the keyboard.

pnpm dlx shadcn add …/r/bottom-sheet.json
Licence
MIT
Packages
2
Updated
12 Nov 2026
Live

Installation

  1. Run this in a project set up with shadcn/ui:

    $ pnpm dlx shadcn@latest add https://uxelith.com/r/bottom-sheet.json
  2. It adds these packages for you:

    clsxtailwind-merge
  3. The source lands in your components folder as bottom-sheet.tsx. It's yours: change anything.

Usage

example.tsx
import { BottomSheet } from "@/components/bottom-sheet"

export function Filters() {
  return (
    <BottomSheet
      trigger={<button type="button">Filters</button>}
      title="Filters"
      description="Narrow the list down."
      snapPoints={[0.5, 0.92]}
    >
      <p className="text-sm text-muted-foreground">Price, distance and opening hours go here.</p>
    </BottomSheet>
  )
}

Source

One file, 584 lines, nothing hidden. Read it before you install it.

bottom-sheet.tsx
"use client";

import * as React from "react";
import { createPortal } from "react-dom";

import { cn } from "@/lib/utils";

// Motion presets (ADR-010). The sheet follows the finger, then settles on this spring, carrying the flick's speed.
const PANEL = { mass: 0.5, stiffness: 220, damping: 26 };
// How far ahead a flick is projected (seconds of its speed) to choose where the sheet lands.
const PROJECT = 0.2;
const NO_DRAG = "input, textarea, select, [contenteditable='true'], [data-no-drag]";

export interface BottomSheetProps extends Omit<React.HTMLAttributes<HTMLDivElement>, "title"> {
  /** Shown or not, when you control it. A non-modal sheet is usually always shown. */
  open?: boolean;
  /** Shown at first. Defaults to shown for a non-modal sheet, hidden for a modal one. */
  defaultOpen?: boolean;
  onOpenChange?: (open: boolean) => void;
  /** A button that opens the sheet. It gets `aria-haspopup`, `aria-expanded`, and focus back on close. */
  trigger?: React.ReactElement<React.ComponentProps<"button">>;
  /**
   * Modal: the page behind dims and can't be used until the sheet closes. Non-modal: the page stays usable
   * (a map, a player) while the sheet rests at its heights.
   */
  modal?: boolean;
  /** Heights it rests at, lowest first: a fraction of the space (0.5) or pixels (120). */
  snapPoints?: number[];
  /** The height it rests at, when you control it: an index into `snapPoints`. */
  snap?: number;
  defaultSnap?: number;
  onSnapChange?: (snap: number) => void;
  /** Names for the heights, read out by screen readers, e.g. ["Peek", "Half", "Full"]. */
  snapLabels?: string[];
  /** Dragging below the lowest height closes it. Defaults to `modal`. */
  dismissible?: boolean;
  /** Names the sheet; shown as its heading. */
  title?: React.ReactNode;
  description?: React.ReactNode;
  /** Sticky actions at the bottom, above the phone's home bar. */
  footer?: React.ReactNode;
  /** Sits inside the nearest positioned parent (a panel, a phone frame) instead of the window. */
  contained?: boolean;
  /** Shrink the page behind a modal sheet, as iOS does. Put `data-sheet-background` on the element that wraps your page. */
  scaleBackground?: boolean;
  /** A text field focused inside rises the sheet to its top height, so the keyboard never hides it. */
  expandOnFocus?: boolean;
}

/** Lets a modal sheet opened from inside another sheet push that one back, as iOS stacks them. */
type Stack = { push: React.RefObject<((progress: number) => void) | null>; host: React.RefObject<HTMLDivElement | null> };
const StackContext = React.createContext<Stack | null>(null);

function prefersReducedMotion() {
  return typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
}

/** Runs PANEL from `from` to `to`, starting at `velocity` px/s, frame by frame. Returns a stop function. */
function settle(from: number, to: number, velocity: number, onFrame: (value: number) => void, onDone?: () => void) {
  if (prefersReducedMotion() || from === to) {
    onFrame(to);
    onDone?.();
    return () => {};
  }
  let x = from;
  let v = velocity;
  let last = performance.now();
  let frame = requestAnimationFrame(function step(now) {
    const dt = Math.min((now - last) / 1000, 1 / 30);
    last = now;
    v += (((to - x) * PANEL.stiffness - v * PANEL.damping) / PANEL.mass) * dt;
    x += v * dt;
    if (Math.abs(to - x) < 0.4 && Math.abs(v) < 10) {
      onFrame(to);
      onDone?.();
      return;
    }
    onFrame(x);
    frame = requestAnimationFrame(step);
  });
  return () => cancelAnimationFrame(frame);
}
type Drag = { id: number; startX: number; startY: number; last: number; time: number; velocity: number; moving: boolean; inBody: boolean; scrolled: boolean };
const noop = () => () => {};
const rubber = (over: number) => Math.sign(over) * Math.sqrt(Math.abs(over)) * 4;

/**
 * A sheet that rises from the bottom and rests at the heights you choose:
 * modal for a focused task, or non-modal beside a map or a player that
 * stays usable behind it.
 *
 * - It follows the finger, then lands where the flick was heading.
 * - Content scrolls at the top height; once it's back at the top, the same
 *   drag carries the sheet down. Below the top height, dragging anywhere
 *   moves the sheet.
 * - A modal sheet opened from inside another sheet pushes that one back.
 * - It rises above the phone's keyboard, and a focused text field lifts it to
 *   its top height.
 * - The handle is a slider: arrow keys, Home and End move between heights,
 *   and the height's name is read out. A modal sheet traps focus, makes the
 *   page behind inert, closes on Escape and gives focus back.
 * - Under `prefers-reduced-motion` it moves straight to each height.
 */
export function BottomSheet({
  open: openProp,
  defaultOpen,
  onOpenChange,
  trigger,
  modal = true,
  snapPoints = [0.5, 0.92],
  snap: snapProp,
  defaultSnap = 0,
  onSnapChange,
  snapLabels,
  dismissible,
  title,
  description,
  footer,
  contained = false,
  scaleBackground = false,
  expandOnFocus = true,
  className,
  style,
  children,
  "aria-label": ariaLabel,
  ...props
}: BottomSheetProps) {
  const id = React.useId();
  const [ownOpen, setOwnOpen] = React.useState(defaultOpen ?? !modal);
  const open = openProp ?? ownOpen;
  // Compared by value, so a new array with the same heights doesn't move the sheet.
  const pointsKey = snapPoints.join(",");
  const points = React.useMemo(() => (pointsKey ? pointsKey.split(",").map(Number) : [0.5]), [pointsKey]);
  const count = points.length;
  const clampSnap = (i: number) => Math.min(Math.max(Math.round(i), 0), count - 1);
  const [ownSnap, setOwnSnap] = React.useState(() => clampSnap(defaultSnap));
  const snap = clampSnap(snapProp ?? ownSnap);
  const canDismiss = dismissible ?? modal;
  // Mounted while open and while sliding away.
  const [present, setPresent] = React.useState(open);
  // False on the server and in the first client render (so hydration matches), true after.
  const mounted = React.useSyncExternalStore(noop, () => true, () => false);
  if (open && !present) setPresent(true);

  const rootRef = React.useRef<HTMLDivElement>(null);
  const sheetRef = React.useRef<HTMLDivElement>(null);
  const bodyRef = React.useRef<HTMLDivElement>(null);
  const backdropRef = React.useRef<HTMLDivElement>(null);
  const triggerRef = React.useRef<HTMLButtonElement>(null);
  const parent = React.useContext(StackContext);
  const parentStack = parent?.push ?? null;
  const myStack = React.useRef<((progress: number) => void) | null>(null);
  const stack = React.useMemo<Stack>(() => ({ push: myStack, host: rootRef }), []);
  const offset = React.useRef<number | null>(null);
  const stopMotion = React.useRef<() => void>(() => {});
  const returnFocus = React.useRef<HTMLElement | null>(null);
  const drag = React.useRef<Drag | null>(null);
  const suppressClick = React.useRef(false);

  const setOpen = React.useCallback(
    (next: boolean) => {
      if (openProp === undefined) setOwnOpen(next);
      onOpenChange?.(next);
    },
    [openProp, onOpenChange],
  );
  const setSnap = React.useCallback(
    (next: number) => {
      if (snapProp === undefined) setOwnSnap(next);
      onSnapChange?.(next);
    },
    [snapProp, onSnapChange],
  );

  // Heights in px for the space the sheet lives in, and the offset (px pushed down) for each.
  const geometry = React.useCallback(() => {
    const space = rootRef.current?.clientHeight || (typeof window === "undefined" ? 800 : window.innerHeight);
    const heights = points.map((p) => (p <= 1 ? p * space : Math.min(p, space)));
    const top = Math.max(...heights);
    return { top, offsets: heights.map((h) => top - h), closed: top + 24 };
  }, [points]);

  // One write per frame: the sheet's transform, the backdrop, the page or parent sheet pushed back.
  const paint = React.useCallback(
    (value: number) => {
      offset.current = value;
      const sheet = sheetRef.current;
      if (!sheet) return;
      sheet.style.transform = `translateY(${value}px)`;
      const { offsets, closed } = geometry();
      const lowest = offsets[0] ?? 0;
      const highest = offsets.at(-1) ?? 0;
      // How "up" the sheet is: 0 closed, 1 at its lowest height (modal) / its top height (non-modal).
      const progress = modal
        ? Math.min(Math.max((closed - value) / Math.max(closed - lowest, 1), 0), 1)
        : count > 1
          ? Math.min(Math.max((offsets.at(-2)! - value) / Math.max(offsets.at(-2)! - highest, 1), 0), 1)
          : 0;
      if (backdropRef.current) backdropRef.current.style.opacity = (modal ? progress : progress * 0.3).toFixed(3);
      if (modal) {
        parentStack?.current?.(progress);
        const page = scaleBackground && !parentStack ? document.querySelector<HTMLElement>("[data-sheet-background]") : null;
        if (page) {
          page.style.transformOrigin = "50% 0";
          page.style.transform = progress > 0 ? `scale(${1 - 0.05 * progress}) translateY(${14 * progress}px)` : "";
          page.style.borderRadius = progress > 0 ? `${12 * progress}px` : "";
          page.style.overflow = progress > 0 ? "hidden" : "";
        }
      }
    },
    [geometry, modal, count, parentStack, scaleBackground],
  );

  // A child modal sheet pushes this one back.
  React.useEffect(() => {
    myStack.current = (progress: number) => {
      const sheet = sheetRef.current;
      if (!sheet) return;
      sheet.style.scale = progress > 0 ? String(1 - 0.06 * progress) : "";
      sheet.style.translate = progress > 0 ? `0 ${-12 * progress}px` : "";
      sheet.style.borderRadius = progress > 0 ? `${16 + 8 * progress}px ${16 + 8 * progress}px 0 0` : "";
    };
  }, []);

  const moveTo = React.useCallback(
    (target: number, velocity = 0, done?: () => void) => {
      stopMotion.current();
      const from = offset.current ?? geometry().closed;
      stopMotion.current = settle(from, target, velocity, paint, done);
    },
    [geometry, paint],
  );

  // Open, close and snap changes move the sheet.
  React.useLayoutEffect(() => {
    if (!present || !sheetRef.current) return;
    const { offsets, closed } = geometry();
    if (open) {
      // A sheet shown from the first paint starts at its height; one that opens slides up from below.
      if (offset.current === null) paint(mounted && (modal || openProp !== undefined || defaultOpen === false) ? closed : offsets[snap]!);
      moveTo(offsets[snap]!);
    } else {
      moveTo(closed, 0, () => {
        setPresent(false);
        offset.current = null;
        parentStack?.current?.(0);
      });
    }
  }, [open, snap, present, mounted, geometry, moveTo, paint, modal, openProp, defaultOpen, parentStack]);
  React.useEffect(() => () => stopMotion.current(), []);

  // The space changing size (rotation, a resized panel) keeps the sheet at its height.
  React.useEffect(() => {
    const root = rootRef.current;
    if (!present || !root || typeof ResizeObserver === "undefined") return;
    const sizes = new ResizeObserver(() => {
      if (open && !drag.current) paint(geometry().offsets[snap]!);
    });
    sizes.observe(root);
    return () => sizes.disconnect();
  }, [present, open, snap, geometry, paint]);

  // Above the on-screen keyboard: the visual viewport shrinks when it opens.
  React.useEffect(() => {
    const vv = window.visualViewport;
    const sheet = sheetRef.current;
    if (!present || contained || !vv || !sheet) return;
    const lift = () => sheet.style.setProperty("--sheet-keyboard", `${Math.max(0, window.innerHeight - vv.height - vv.offsetTop)}px`);
    vv.addEventListener("resize", lift);
    vv.addEventListener("scroll", lift);
    lift();
    return () => {
      vv.removeEventListener("resize", lift);
      vv.removeEventListener("scroll", lift);
    };
  }, [present, contained]);

  // Modal: the rest of the page is inert, the page stops scrolling, focus moves in and comes back on close.
  React.useEffect(() => {
    const root = rootRef.current;
    if (!modal || !open || !present || !root?.parentElement) return;
    returnFocus.current = (document.activeElement as HTMLElement | null) ?? triggerRef.current;
    const quieted = [...root.parentElement.children].filter((el): el is HTMLElement => el !== root && el instanceof HTMLElement && !el.hasAttribute("inert"));
    for (const el of quieted) el.setAttribute("inert", "");
    const html = document.documentElement;
    const overflow = html.style.overflow;
    if (!contained) html.style.overflow = "hidden";
    const frame = requestAnimationFrame(() => {
      // The first thing to use in the content, else the close button, else the sheet itself.
      const sheet = sheetRef.current;
      const focusable = "[autofocus], input, textarea, select, button, a[href], [tabindex]:not([tabindex='-1'])";
      const first = bodyRef.current?.querySelector<HTMLElement>(focusable) ?? sheet?.querySelector<HTMLElement>("button[aria-label='Close']");
      (first ?? sheet)?.focus({ preventScroll: true });
    });
    return () => {
      cancelAnimationFrame(frame);
      for (const el of quieted) el.removeAttribute("inert");
      if (!contained) html.style.overflow = overflow;
      const back = returnFocus.current;
      if (back?.isConnected) back.focus({ preventScroll: true });
    };
  }, [modal, open, present, contained]);

  // ---- Dragging ----

  const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
    const target = event.target as HTMLElement;
    // React bubbles events from a sheet portalled out of this one; those belong to that sheet.
    if (!event.currentTarget.contains(target) || event.button !== 0 || target.closest(NO_DRAG)) return;
    const inBody = !!bodyRef.current?.contains(target);
    // A mouse scrolls the content with its wheel; it drags the sheet by the handle and header.
    if (inBody && event.pointerType === "mouse") return;
    stopMotion.current();
    drag.current = { id: event.pointerId, startX: event.clientX, startY: event.clientY, last: event.clientY, time: event.timeStamp, velocity: 0, moving: false, inBody, scrolled: false };
  };

  const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {
    const d = drag.current;
    if (!d || d.id !== event.pointerId) return;
    if (!d.moving) {
      const dy = Math.abs(event.clientY - d.startY);
      const dx = Math.abs(event.clientX - d.startX);
      if (dy < 6 && dx < 6) return;
      // Sideways is a swipe for something inside (a carousel), not the sheet.
      if (dx > dy) {
        drag.current = null;
        return;
      }
      d.moving = true;
      event.currentTarget.setPointerCapture?.(event.pointerId);
    }
    const delta = event.clientY - d.last;
    const dt = Math.max(event.timeStamp - d.time, 1);
    d.velocity = 0.8 * ((delta / dt) * 1000) + 0.2 * d.velocity;
    d.last = event.clientY;
    d.time = event.timeStamp;
    const { offsets, closed } = geometry();
    const top = offsets.at(-1)!;
    const lowest = offsets[0]!;
    let next = (offset.current ?? top) + delta;
    const body = bodyRef.current;
    // At the top height the content scrolls first; at its top, the rest of a downward drag moves the sheet.
    if (d.inBody && body && (offset.current ?? top) <= top + 0.5) {
      const room = body.scrollHeight - body.clientHeight;
      if (delta < 0 && body.scrollTop < room) {
        body.scrollTop = Math.min(body.scrollTop - delta, room);
        d.scrolled = true;
        return;
      }
      if (delta > 0 && body.scrollTop > 0) {
        const before = body.scrollTop;
        body.scrollTop = Math.max(before - delta, 0);
        d.scrolled = true;
        const left = delta - (before - body.scrollTop);
        if (left <= 0) return;
        next = top + left;
      }
    }
    d.scrolled = false;
    if (next < top) next = top - rubber(top - next);
    const floor = canDismiss ? closed : lowest;
    if (next > floor) next = floor + rubber(next - floor);
    paint(next);
  };

  const onPointerUp = (event: React.PointerEvent<HTMLDivElement>) => {
    const d = drag.current;
    drag.current = null;
    if (!d?.moving || d.id !== event.pointerId) return;
    suppressClick.current = true;
    const body = bodyRef.current;
    if (d.scrolled && body) {
      // The content keeps the flick's momentum.
      let v = -d.velocity;
      if (prefersReducedMotion()) return;
      let last = performance.now();
      const glide = (now: number) => {
        const dt = (now - last) / 1000;
        last = now;
        v *= Math.pow(0.05, dt);
        const before = body.scrollTop;
        body.scrollTop += v * dt;
        if (Math.abs(v) > 30 && body.scrollTop !== before) requestAnimationFrame(glide);
      };
      requestAnimationFrame(glide);
      return;
    }
    const { offsets, closed } = geometry();
    const projected = (offset.current ?? 0) + d.velocity * PROJECT;
    const stops = canDismiss ? [...offsets, closed] : offsets;
    const nearest = stops.reduce((best, stop, i) => (Math.abs(stop - projected) < Math.abs(stops[best]! - projected) ? i : best), 0);
    if (nearest === offsets.length) {
      stopMotion.current();
      stopMotion.current = settle(offset.current ?? 0, closed, d.velocity, paint);
      setOpen(false);
      return;
    }
    if (nearest === snap) moveTo(offsets[nearest]!, d.velocity);
    else {
      moveTo(offsets[nearest]!, d.velocity);
      setSnap(nearest);
    }
  };

  const onPointerCancel = () => {
    if (drag.current?.moving) moveTo(geometry().offsets[snap]!);
    drag.current = null;
  };

  const labelFor = (i: number) => snapLabels?.[i] ?? (count === 1 ? "Open" : i === 0 ? "Lowest" : i === count - 1 ? "Highest" : `Height ${i + 1} of ${count}`);

  const panel = present && (
    <StackContext.Provider value={stack}>
      <div
        ref={rootRef}
        data-bottom-sheet={modal ? "modal" : "inline"}
        className={cn("pointer-events-none inset-0 z-50 overflow-hidden", contained ? "absolute" : "fixed")}
      >
        {(modal || count > 1) && (
          <div
            ref={backdropRef}
            aria-hidden="true"
            onClick={modal ? () => setOpen(false) : undefined}
            className={cn("absolute inset-0 bg-black/50", modal ? "pointer-events-auto" : "pointer-events-none")}
            style={{ opacity: 0 }}
          />
        )}
        <div
          ref={sheetRef}
          role={modal ? "dialog" : "region"}
          aria-modal={modal || undefined}
          aria-labelledby={title ? `${id}-title` : undefined}
          aria-label={title ? undefined : (ariaLabel ?? "Sheet")}
          aria-describedby={description ? `${id}-description` : undefined}
          tabIndex={-1}
          onPointerDown={onPointerDown}
          onPointerMove={onPointerMove}
          onPointerUp={onPointerUp}
          onPointerCancel={onPointerCancel}
          onClickCapture={(event) => {
            // A drag that ends over a button isn't a press.
            if (suppressClick.current && event.currentTarget.contains(event.target as Node)) {
              suppressClick.current = false;
              event.stopPropagation();
              event.preventDefault();
            }
          }}
          onKeyDown={(event) => {
            if (!event.currentTarget.contains(event.target as Node)) return;
            if (event.key === "Escape" && !event.defaultPrevented) {
              event.preventDefault();
              event.stopPropagation();
              if (modal) setOpen(false);
              else if (snap > 0) setSnap(0);
            }
            if (modal && event.key === "Tab") {
              const items = [...event.currentTarget.querySelectorAll<HTMLElement>("button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])")].filter((el) => !el.hasAttribute("disabled") && !el.closest("[inert]"));
              if (!items.length) return;
              const first = items[0]!;
              const last = items.at(-1)!;
              if (event.shiftKey && (document.activeElement === first || document.activeElement === event.currentTarget)) {
                event.preventDefault();
                last.focus();
              } else if (!event.shiftKey && document.activeElement === last) {
                event.preventDefault();
                first.focus();
              }
            }
          }}
          onFocus={(event) => {
            if (!event.currentTarget.contains(event.target as Node) || !expandOnFocus || snap === count - 1) return;
            const field = event.target as HTMLElement;
            if (field.matches("input:not([type=checkbox]):not([type=radio]):not([type=range]):not([type=button]):not([type=submit]), textarea, [contenteditable='true']")) setSnap(count - 1);
          }}
          className={cn(
            "pointer-events-auto absolute inset-x-0 bottom-[var(--sheet-keyboard,0px)] mx-auto flex max-w-2xl touch-none flex-col rounded-t-2xl border-t border-border bg-background text-foreground shadow-[0_-12px_40px_-16px_rgb(0_0_0/0.35)] outline-none",
            className,
          )}
          style={{
            height: `max(${points.map((p) => (p <= 1 ? `${p * 100}%` : `${p}px`)).join(", ")})`,
            maxHeight: "100%",
            transform: `translateY(calc(max(${points.map((p) => (p <= 1 ? `${p * 100}%` : `${p}px`)).join(", ")}) - ${points[snap]! <= 1 ? `${points[snap]! * 100}%` : `${points[snap]}px`}))`,
            ...style,
          }}
          {...props}
        >
          {/* A slider: keyboard and screen-reader users move between heights; a tap moves to the next one. */}
          <button
            type="button"
            data-sheet-handle=""
            role="slider"
            aria-label={title && typeof title === "string" ? `${title} height` : "Sheet height"}
            aria-orientation="vertical"
            aria-valuemin={0}
            aria-valuemax={count - 1}
            aria-valuenow={snap}
            aria-valuetext={labelFor(snap)}
            onClick={() => count > 1 && setSnap((snap + 1) % count)}
            onKeyDown={(event) => {
              const step = { ArrowUp: 1, ArrowRight: 1, ArrowDown: -1, ArrowLeft: -1, PageUp: 1, PageDown: -1 }[event.key];
              if (step) {
                event.preventDefault();
                setSnap(clampSnap(snap + step));
              } else if (event.key === "Home") {
                event.preventDefault();
                setSnap(0);
              } else if (event.key === "End") {
                event.preventDefault();
                setSnap(count - 1);
              }
            }}
            className="group/handle flex w-full shrink-0 cursor-grab justify-center pb-1.5 pt-3 outline-none active:cursor-grabbing"
          >
            <span className="h-1.5 w-10 rounded-full bg-muted-foreground/30 transition-[width,background-color] duration-200 group-hover/handle:w-12 group-focus-visible/handle:bg-ring" />
          </button>
          {(title || description || modal) && (
            <header className="flex shrink-0 items-start justify-between gap-4 px-5 pb-3">
              <div className="grid min-w-0 gap-0.5">
                {title && (
                  <h2 id={`${id}-title`} className="text-lg font-semibold tracking-tight">
                    {title}
                  </h2>
                )}
                {description && (
                  <p id={`${id}-description`} className="text-sm text-muted-foreground">
                    {description}
                  </p>
                )}
              </div>
              {modal && (
                <button
                  type="button"
                  aria-label="Close"
                  onClick={() => setOpen(false)}
                  className="-mr-1.5 grid size-8 shrink-0 place-items-center rounded-full text-muted-foreground outline-none transition-colors duration-150 hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
                >
                  <svg viewBox="0 0 16 16" aria-hidden="true" className="size-4" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round">
                    <path d="M4 4l8 8M12 4l-8 8" />
                  </svg>
                </button>
              )}
            </header>
          )}
          <div
            ref={bodyRef}
            onWheel={(event) => {
              // A wheel down on a lower height raises the sheet first, then the content scrolls.
              if (event.deltaY > 0 && snap < count - 1 && !event.ctrlKey) setSnap(count - 1);
            }}
            // Touch scrolling is driven by the drag code (so it can hand off to the sheet); wheel and keys scroll natively.
            className={cn("min-h-0 flex-1 touch-none overscroll-contain px-5 pb-5", snap === count - 1 ? "overflow-y-auto" : "overflow-hidden")}
          >
            {children}
          </div>
          {footer && <footer className="flex shrink-0 flex-wrap justify-end gap-2 border-t border-border px-5 pb-[max(1rem,env(safe-area-inset-bottom))] pt-3">{footer}</footer>}
          {!footer && <div aria-hidden="true" className="h-[env(safe-area-inset-bottom)] shrink-0" />}
        </div>
      </div>
    </StackContext.Provider>
  );

  return (
    <>
      {trigger &&
        React.cloneElement(trigger, {
          ref: triggerRef,
          "aria-haspopup": "dialog",
          "aria-expanded": open,
          onClick: (event: React.MouseEvent<HTMLButtonElement>) => {
            trigger.props.onClick?.(event);
            if (!event.defaultPrevented) setOpen(!open);
          },
        } as React.ComponentProps<"button">)}
      {panel && (contained && parent ? (
        // Opened from inside another contained sheet: it covers the same frame, not just that sheet.
        mounted && parent.host.current?.parentElement ? createPortal(panel, parent.host.current.parentElement) : null
      ) : modal && !contained ? (
        mounted ? createPortal(panel, document.body) : null
      ) : (
        panel
      ))}
    </>
  );
}

Props

PropTypeDefaultDescription
openboolean—Shown or not, when you control it.
defaultOpenbooleanmodal ? false : trueShown at first.
onOpenChange(open: boolean) => void—Called when it opens or closes.
triggerReactElement<button>—A button that opens it; gets aria-haspopup, aria-expanded and focus back on close.
modalbooleantrueModal dims the page and traps focus; non-modal keeps the page behind usable.
snapPointsnumber[][0.5, 0.92]Heights it rests at, lowest first: a fraction of the space or pixels.
snapnumber—The height it rests at, when you control it (an index into snapPoints).
defaultSnapnumber0The first height.
onSnapChange(snap: number) => void—Called when it settles at another height.
snapLabelsstring[]—Names for the heights, read out by screen readers.
dismissiblebooleanmodalDragging below the lowest height closes it.
titleReactNode—Names the sheet; shown as its heading.
descriptionReactNode—Shown under the title and read out with it.
footerReactNode—Sticky actions at the bottom, above the home bar.
containedbooleanfalseSits inside the nearest positioned parent instead of the window.
scaleBackgroundbooleanfalseShrinks the page behind a modal sheet (put data-sheet-background on it).
expandOnFocusbooleantrueA focused text field raises the sheet to its top height.
...propsHTMLAttributes<HTMLDivElement>—Passed to the sheet panel.

Accessibility

  • The handle is a vertical slider: arrow keys, Page Up/Down, Home and End move between heights, and each height's name is read out.
  • A modal sheet is a labelled dialog: focus moves in and is trapped, the rest of the page is inert, Escape closes it and focus returns to what opened it.
  • A non-modal sheet is a labelled region; the page behind stays usable, and Escape lowers it.
  • Everything you can do by dragging you can do with the handle, the close button or the keyboard.
  • Under prefers-reduced-motion it moves straight to each height.

Changelog

  1. v1.0.0Latest

    First release.

More in Navigation

All 10 in Navigation
  • NavigationFree

    Accordion

    Questions that spring open to their answers — reversible mid-way — with a hover highlight that glides between titles and a plus that folds into a minus (or a chevron). Single or multiple open, two looks.

  • NavigationFree

    Animated Tabs

    Tabs with an indicator that springs to the selected tab, a hover highlight that follows the pointer, and panels that slide in from the side you're heading to while the height eases to fit. Pill or underline.

  • NavigationFree

    Bottom Tab Bar

    The row of sections along the bottom of a phone app: classic, floating or liquid-glass, with a marker that glides between tabs, count badges and a raised middle action. Tabs can be real links, so every section stays crawlable.