useHeadroom
useHeadroom (스크롤 감지 헤더)
useHeadroom 훅은 사용자가 주어진 거리(픽셀)만큼 스크롤한 뒤에 숨겨지는 헤더를 만들 수 있게 해줘요. { pinned, scrollProgress }를 반환해요.
출처: 문서
본문
useHeadroom 훅은 사용자가 주어진 거리(픽셀)만큼 스크롤한 뒤 숨겨지는 헤더를 만들 수 있게 해줘요. 요소가 적어도 일부라도 보이면 pinned가 true가 되고, scrollProgress는 0(완전히 숨김)에서 1(완전히 보임) 사이의 숫자를 반환해요.
import { Box, Button, Group, Portal, Text } from '@mantine/core';
import { useDisclosure, useHeadroom } from '@mantine/hooks';
function Demo() {
const [showHeader, handlers] = useDisclosure(false);
const { pinned } = useHeadroom({ fixedAt: 120 });
return (
<>
{showHeader && (
<Portal>
<Box
style={{
position: 'fixed',
top: pinned ? 0 : -80,
transition: 'top 200ms ease-in-out',
background: 'var(--mantine-color-body)',
borderBottom: '1px solid',
borderColor: 'var(--mantine-color-gray-3)',
width: '100%',
}}
>
<Text p="md">Pinned header – {pinned ? 'visible' : 'hidden'}</Text>
</Box>
</Portal>
)}
<Button onClick={handlers.toggle}>
{showHeader ? 'Hide' : 'Show'} header
</Button>
</>
);
}
scrollProgress
즉각적인 표시/숨김 토글 대신 스크롤 연동 리빌(reveal) 애니메이션을 만들려면 scrollProgress를 사용해요. 사용자가 fixedAt을 지나 아래로 스크롤하면 이 값은 1(완전히 보임)에서 0(완전히 숨김)으로 전환되고, 위로 스크롤하면 다시 1로 돌아가요. 스크롤 도중 방향 변경은 올바르게 처리돼요. 요소를 완전히 드러내거나 숨기는 데 필요한 스크롤 픽셀 수를 제어하려면 scrollDistance를 설정하세요.
const { scrollProgress } = useHeadroom({ fixedAt: 120, scrollDistance: 60 });
콜백 (Callbacks)
이 훅은 onPin, onRelease, onFix 콜백을 지원해요.
onPin— 헤더가 보이게 될 때 호출돼요 (사용자가 위로 스크롤)onRelease— 헤더가 숨겨질 때 호출돼요 (사용자가 아래로 스크롤)onFix— 스크롤 위치가 고정 구역(스크롤 위치 ≤fixedAt)에 들어올 때 호출돼요
const { pinned } = useHeadroom({
fixedAt: 80,
onPin: () => addLog('onPin'),
onRelease: () => addLog('onRelease'),
onFix: () => addLog('onFix'),
});
정의 (Definition)
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
UseHeadroomOptions 타입은 @mantine/hooks에서 내보내져요.
import { UseHeadroomOptions } from '@mantine/hooks';