use-headroom

Create headers that are hidden after user scrolls past given distance

Import

Usage

Use use-headroom hook to create headers that are hidden after user scrolls past the given distance in px. The hook returns a boolean value that determines whether the element should be pinned or hidden. Hook returns true when the current scroll position is less than the specified fixedAt value and after user scrolled up.

Header is pinned

import { Box, Portal, rem, Text } from '@mantine/core';
import { useHeadroom } from '@mantine/hooks';

function Demo() {
  const pinned = useHeadroom({ fixedAt: 120 });

  return (
    <>
      <Portal>
        <Box
          style={{
            position: 'fixed',
            top: 0,
            left: 0,
            right: 0,
            padding: 'var(--mantine-spacing-xs)',
            height: rem(60),
            zIndex: 1000000,
            transform: `translate3d(0, ${pinned ? 0 : rem(-110)}, 0)`,
            transition: 'transform 400ms ease',
            backgroundColor: 'var(--mantine-color-body)',
          }}
        >
          Pinned header
        </Box>
      </Portal>
      <Text ta="center">Header is {pinned ? 'pinned' : 'not pinned'}</Text>
    </>
  );
}

Definition

function useHeadroom(input?: {
  /** Number in px at which element should be fixed */
  fixedAt?: number;

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

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

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