Back to Mantine

Use Headroom

apps/mantine.dev/src/pages/hooks/use-headroom.mdx

9.4.12.3 KB
Original Source

import { UseHeadroomDemos } from '@docs/demos'; import { Layout } from '@/layout'; import { MDX_DATA } from '@/mdx';

export default Layout(MDX_DATA.useHeadroom);

Usage

The use-headroom hook creates headers that are hidden after the user scrolls past a given distance in pixels. It returns { pinned, scrollProgress } where pinned is true when the element is at least partially visible and scrollProgress is a number between 0 (fully hidden) and 1 (fully visible).

<Demo data={UseHeadroomDemos.usage} />

scrollProgress

Use scrollProgress to create a scroll-linked reveal animation instead of an instant show/hide toggle. The value transitions from 1 (fully visible) to 0 (fully hidden) as the user scrolls down past fixedAt, and back to 1 as the user scrolls up. Direction changes mid-scroll are handled correctly — the progress continues from wherever it was when the direction changed. Set scrollDistance to control how many pixels of scrolling are needed to fully reveal or hide the element.

<Demo data={UseHeadroomDemos.scrollProgress} />

Callbacks

The hook supports onPin, onRelease, and onFix callbacks:

  • onPin is called when the header becomes visible (user scrolls up)
  • onRelease is called when the header is hidden (user scrolls down)
  • onFix is called when the scroll position enters the fixed zone (scroll position ≤ fixedAt)
<Demo data={UseHeadroomDemos.callbacks} />

Definition

tsx
interface UseHeadroomOptions {
  /** Number in px at which element should be fixed, 0 by default */
  fixedAt?: number;

  /** Number of px to scroll to fully reveal or hide the element, 100 by default */
  scrollDistance?: number;

  /** Called when element is pinned */
  onPin?: () => void;

  /** Called when element is at fixed position */
  onFix?: () => void;

  /** Called when element is unpinned */
  onRelease?: () => void;
}

interface UseHeadroomReturnValue {
  /** True when the element is at least partially visible */
  pinned: boolean;

  /** Reveal progress: 0 = fully hidden, 1 = fully visible */
  scrollProgress: number;
}

function useHeadroom(input?: UseHeadroomOptions): UseHeadroomReturnValue;

Exported types

The UseHeadroomOptions type is exported from @mantine/hooks;

tsx
import { UseHeadroomOptions } from '@mantine/hooks';