TableOfContents
TableOfContents
페이지의 제목(heading) 목록을 렌더링하고, 뷰포트에 보이는 현재 제목을 추적하는 목차 컴포넌트예요.
출처: 문서
본문
사용법 (Usage)
TableOfContents 컴포넌트를 사용해 mantine.dev 문서의 사이드바와 같은 목차를 표시해요. 이 컴포넌트는 스크롤 위치를 추적하고 목록에서 현재 제목을 강조해요.
import { TableOfContents } from '@mantine/core';
function Demo() {
return (
<TableOfContents
getControlProps={({ data }) => ({
onClick: () => data.getNode().scrollIntoView(),
children: data.value,
})}
/>
);
}
use-scroll-spy 옵션 (use-scroll-spy options)
TableOfContents는 use-scroll-spy 훅을 기반으로 해요. scrollSpyOptions prop을 사용해 use-scroll-spy 훅에 옵션을 전달할 수 있어요.
선택자, 깊이, 값 추출을 커스터마이즈하는 예시:
import { TableOfContents } from '@mantine/core';
function Demo() {
return (
<TableOfContents
scrollSpyOptions={{
selector: '[data-heading]',
getDepth: (element) => Number(element.getAttribute('data-order')),
getValue: (element) => element.getAttribute('data-heading') || '',
}}
/>
);
}
컨트롤에 props 전달하기 (Pass props to controls)
getControlProps 함수로 TableOfContents 컴포넌트가 렌더링하는 컨트롤에 props를 전달할 수 있어요. active와 data 속성을 가진 객체를 받아 props 객체를 반환해요.
컨트롤을 링크로 바꾸는 예시:
import { TableOfContents } from '@mantine/core';
function Demo() {
return (
<TableOfContents
getControlProps={({ data, active }) => ({
component: 'a',
href: `#${data.id}`,
style: { color: active ? 'blue' : 'gray' },
children: data.value,
})}
/>
);
}
초기 데이터 (Initial data)
TableOfContents는 마운트될 때 데이터를 가져와요. TableOfContents 컴포넌트가 마운트되기 전에(예: 서버 사이드 렌더링 중) 제목을 렌더링하고 싶다면, 제목 데이터의 배열과 함께 initialData prop을 전달할 수 있어요. initialData는 마운트 시 실제 데이터로 교체돼요.
import { TableOfContents } from '@mantine/core';
function Demo() {
return (
<TableOfContents
initialData={[
{ value: 'Usage', id: 'usage', order: 1 },
// ...더 많은 제목 데이터
]}
/>
);
}
깊이 오프셋 (Depth offset)
minDepthToOffset prop으로 오프셋을 적용할 최소 깊이를 설정할 수 있어요. 기본적으로 minDepthToOffset은 1이라, 1·2레벨 제목은 오프셋이 적용되지 않아요. 모든 제목에 오프셋을 적용하려면 0으로 설정해요.
px 단위의 오프셋 값을 제어하려면 depthOffset prop을 설정해요.
import { TableOfContents } from '@mantine/core';
function Demo() {
return (
<TableOfContents
minDepthToOffset={1}
depthOffset={8}
getControlProps={({ data }) => ({
onClick: () => data.getNode().scrollIntoView(),
children: data.value,
})}
/>
);
}
autoContrast
TableOfContents는 autoContrast prop과 theme.autoContrast를 지원해요. TableOfContents나 테마에 autoContrast를 설정하면, color prop에 지정된 값과 충분한 대비를 가지도록 콘텐츠 색상이 조정돼요.
autoContrast 기능은 color prop으로 배경색을 변경할 때만 동작한다는 점에 주의해요. autoContrast는 filled variant에서만 동작해요.
import { TableOfContents } from '@mantine/core';
function Demo() {
return (
<TableOfContents
color="blue"
autoContrast
getControlProps={({ data }) => ({
onClick: () => data.getNode().scrollIntoView(),
children: data.value,
})}
/>
);
}
Styles API
Styles API와 data-* attributes로 TableOfContents를 커스터마이즈하는 예시:
import { TableOfContents } from '@mantine/core';
import classes from './Demo.module.css';
function Demo() {
return (
<TableOfContents
classNames={classes}
getControlProps={({ data }) => ({
onClick: () => data.getNode().scrollIntoView(),
children: data.value,
})}
/>
);
}
다시 초기화하기 (Reinitialize)
기본적으로 TableOfContents는 DOM의 변경을 추적하지 않아요. 부모 컴포넌트가 마운트된 후 제목 데이터를 갱신하고 싶다면, reinitializeRef로 use-scroll-spy 훅에서 다시 초기화 함수를 가져올 수 있어요.
import { useRef, useLayoutEffect } from 'react';
import { TableOfContents } from '@mantine/core';
function Demo({ dependency }) {
const reinitializeRef = useRef(() => {});
useLayoutEffect(() => {
reinitializeRef.current();
}, [dependency]);
return <TableOfContents reinitializeRef={reinitializeRef} />;
}