use-scroll-spy
use-scroll-spy
스크롤 위치에 따라 현재 활성화된 섹션(헤딩)을 추적하는 훅이에요. 스크롤 목차(TOC)에 유용해요.
출처: 문서
본문
ref는 컴포넌트가 마운트된 후 effect 안에서 해석되므로, 첫 렌더링에서 스크롤 호스트가 존재할 필요는 없어요. 일반 ref 객체는 반응형이 아니라는 점에 주의해요. 나중에 ref를 다른 엘리먼트로 바꾸면 훅은 원래 엘리먼트에 리스너를 유지해요. 스크롤 호스트 자체가 런타임 중에 바뀔 수 있다면, 해석된 엘리먼트를 state를 통해 넘겨 scrollHost의 정체성이 바뀌어 훅이 새 값으로 다시 실행되도록 해요.
훅 데이터 재초기화 (Reinitializing hook data)
기본적으로 use-scroll-spy는 DOM의 변화를 추적하지 않아요. 부모 컴포넌트가 마운트된 후 헤딩 데이터를 업데이트하려면 reinitialize 함수를 사용할 수 있어요.
import { useEffect } from 'react';
import { useScrollSpy } from '@mantine/hooks';
function Demo({ dependency }) {
const { reinitialize } = useScrollSpy();
useEffect(() => {
reinitialize();
}, [dependency]);
return null;
}
정의 (Definition)
정의에 사용된 모든 타입은 @mantine/hooks 패키지에서 내보내져요.
interface UseScrollSpyHeadingData {
/** Heading depth, 1-6 */
depth: number;
/** Heading text content value */
value: string;
/** Heading id */
id: string;
/** Function to get heading node */
getNode: () => HTMLElement;
}
interface UseScrollSpyOptions {
/** Selector to get headings, `'h1, h2, h3, h4, h5, h6'` by default */
selector?: string;
/** A function to retrieve depth of heading, by default depth is calculated based on tag name */
getDepth?: (element: HTMLElement) => number;
/** A function to retrieve heading value, by default `element.textContent` is used */
getValue?: (element: HTMLElement) => string;
/** Host element or a ref to it to attach scroll event listener, if not provided, `window` is used */
scrollHost?: HTMLElement | React.RefObject;
/** Offset from the top of the viewport to use when determining the active heading, `0` by default */
offset?: number;
}
interface UseScrollSpyReturnValue {
/** Index of the active heading in the `data` array */
active: number;
/** Headings data. If not initialize, data is represented by an empty array. */
data: UseScrollSpyHeadingData[];
/** True if headings value have been retrieved from the DOM. */
initialized: boolean;
/** Function to update headings values after the parent component has mounted. */
reinitialize: () => void;
}
function useScrollSpy(options?: UseScrollSpyOptions): UseScrollSpyReturnValue
내보내는 타입 (Exported types)
UseScrollSpyOptions와 UseScrollSpyReturnValue 타입은 @mantine/hooks 패키지에서 내보내져요. 애플리케이션에서 임포트할 수 있어요.
import type { UseScrollSpyOptions, UseScrollSpyReturnValue } from '@mantine/hooks';