본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

목차

원문 보기 위키 갱신

목차 (Table of Contents)

사용자가 문서 콘텐츠를 스크롤할 때 활성 섹션을 추적하고 강조 표시하는 탐색 컴포넌트입니다. 문서의 현재 읽기 위치를 반영하는 목차를 제공합니다.

출처: 문서

본문

해부 구조 (Anatomy)

<Toc.Root items={items} scrollEl={() => scrollContainer}>
  <Toc.Content />
  <Toc.Nav>
    <Toc.Title />
    <Toc.List>
      <Toc.Indicator />
      <Toc.Item item={item}>
        <Toc.Link />
      </Toc.Item>
    </Toc.List>
  </Toc.Nav>
</Toc.Root>

예시 (Examples)

기본 (Basic)

items에 제목들을 전달하고, scrollEl을 스크롤 가능한 컨테이너를 가리키도록 설정하면 목차가 무엇을 추적할지 알 수 있습니다.

import { Toc } from '@ark-ui/react/toc'
import { useRef } from 'react'
import styles from 'styles/toc.module.css'

const items = [
  { value: '01-introduction', depth: 2, label: 'Introduction', lines: 12 },
  { value: '01-getting-started', depth: 2, label: 'Getting Started', lines: 10 },
  { value: '01-installation', depth: 2, label: 'Installation', lines: 8 },
  { value: '01-usage', depth: 2, label: 'Usage', lines: 14 },
  { value: '01-conclusion', depth: 2, label: 'Conclusion', lines: 10 },
]

export const Basic = () => {
  const contentRef = useRef<HTMLElement | null>(null)

  return (
    <Toc.Root className={styles.Root} items={items} scrollEl={() => contentRef.current}>
      <Toc.Content className={styles.Content} ref={contentRef}>
        {items.map((item) => (
          <section key={item.value} className={styles.Section}>
            <h2 id={item.value} className={styles.Heading} data-depth={item.depth}>
              {item.label}
            </h2>
            <div className={styles.DummyText}>
              {Array.from({ length: item.lines }).map((_, i) => (
                <div key={i} className={styles.DummyLine} />
              ))}
            </div>
          </section>
        ))}
      </Toc.Content>

      <Toc.Nav className={styles.Nav}>
        <Toc.Title className={styles.Title}>On this page</Toc.Title>
        <Toc.List className={styles.List}>
          {items.map((item) => (
            <Toc.Item className={styles.Item} key={item.value} item={item}>
              <Toc.Link className={styles.Link} href={`#${item.value}`}>
                {item.label}
              </Toc.Link>
            </Toc.Item>
          ))}
        </Toc.List>
      </Toc.Nav>
    </Toc.Root>
  )
}

중첩된 제목 (Nested Headings)

자신의 마크업에서 depth를 읽어 하위 제목을 들여쓰기하세요. 아무것도 자동으로 들여쓰기되지 않습니다.

import { Toc } from '@ark-ui/react/toc'
import { useRef } from 'react'
import styles from 'styles/toc.module.css'

const items = [
  { value: '02-importance', depth: 2, label: 'Importance', lines: 10 },
  { value: '02-integrations', depth: 2, label: 'Integrations', lines: 12 },
  { value: '02-free-blocks', depth: 3, label: 'Free Blocks', lines: 8 },
  { value: '02-configuration', depth: 3, label: 'Configuration', lines: 14 },
  { value: '02-api-reference', depth: 2, label: 'API Reference', lines: 10 },
  { value: '02-hooks', depth: 3, label: 'Hooks', lines: 8 },
  { value: '02-components', depth: 3, label: 'Components', lines: 12 },
  { value: '02-examples', depth: 2, label: 'Examples', lines: 10 },
]

export const Nested = () => {
  const contentRef = useRef<HTMLElement | null>(null)

  return (
    <Toc.Root className={`${styles.Root}`} items={items} scrollEl={() => contentRef.current}>
      <Toc.Content className={styles.Content} ref={contentRef}>
        {items.map((item) => (
          <section key={item.value}>
            <div id={item.value} className={styles.Heading} data-depth={item.depth}>
              {item.label}
            </div>
            <div className={styles.DummyText}>
              {Array.from({ length: item.lines }).map((_, i) => (
                <div key={i} className={styles.DummyLine} />
              ))}
            </div>
          </section>
        ))}
      </Toc.Content>

      <Toc.Nav className={styles.Nav}>
        <Toc.Title className={styles.Title}>On this page</Toc.Title>
        <Toc.List className={styles.List}>
          {items.map((item) => (
            <Toc.Item className={item.depth > 2 ? styles.ItemNested : styles.Item} key={item.value} item={item}>
              <Toc.Link className={styles.Link} href={`#${item.value}`}>
                {item.label}
              </Toc.Link>
            </Toc.Item>
          ))}
        </Toc.List>
      </Toc.Nav>
    </Toc.Root>
  )
}

루트 프로바이더 (Root Provider)

useToc을 Toc.RootProvider와 함께 사용하면 트리 외부에서 activeIds에 접근할 수 있어, UI의 다른 부분이 읽기 위치를 따라갈 수 있습니다.

import { Toc, useToc } from '@ark-ui/react/toc'
import { useRef } from 'react'
import styles from 'styles/toc.module.css'

const items = [
  { value: '03-introduction', depth: 2, label: 'Introduction', lines: 12 },
  { value: '03-getting-started', depth: 2, label: 'Getting Started', lines: 10 },
  { value: '03-installation', depth: 2, label: 'Installation', lines: 8 },
  { value: '03-usage', depth: 2, label: 'Usage', lines: 14 },
  { value: '03-conclusion', depth: 2, label: 'Conclusion', lines: 10 },
]

export const RootProvider = () => {
  const contentRef = useRef<HTMLElement | null>(null)

  const toc = useToc({
    items,
    scrollEl: () => contentRef.current,
  })

  return (
    <div className="vstack" style={{ width: '100%' }}>
      <output>activeIds: {JSON.stringify(toc.activeIds)}</output>
      <Toc.RootProvider className={styles.Root} value={toc}>
        <Toc.Content className={styles.Content} ref={contentRef}>
          {items.map((item) => (
            <section key={item.value} className={styles.Section}>
              <h2 id={item.value} className={styles.Heading} data-depth={item.depth}>
                {item.label}
              </h2>
              <div className={styles.DummyText}>
                {Array.from({ length: item.lines }).map((_, i) => (
                  <div key={i} className={styles.DummyLine} />
                ))}
              </div>
            </section>
          ))}
        </Toc.Content>

        <Toc.Nav className={styles.Nav}>
          <Toc.Title className={styles.Title}>On this page</Toc.Title>
          <Toc.List className={styles.List}>
            {items.map((item) => (
              <Toc.Item className={styles.Item} key={item.value} item={item}>
                <Toc.Link className={styles.Link} href={`#${item.value}`}>
                  {item.label}
                </Toc.Link>
              </Toc.Item>
            ))}
          </Toc.List>
        </Toc.Nav>
      </Toc.RootProvider>
    </div>
  )
}

Collapsible과 함께 (With Collapsible)

Toc.Nav를 Collapsible로 감싸서 사용자가 탐색을 숨길 수 있게 하세요. Toc.Context는 activeItems를 노출하며, 여기서 진행 링(progress ring)을 구동합니다.

import { Collapsible } from '@ark-ui/react/collapsible'
import { Toc } from '@ark-ui/react/toc'
import { ChevronRightIcon } from 'lucide-react'
import CollapsibleStyles from 'styles/collapsible.module.css'
import styles from 'styles/toc.module.css'
import { useRef } from 'react'

const items = [
  { value: '04-overview', depth: 2, label: 'Overview', lines: 8 },
  { value: '04-prerequisites', depth: 2, label: 'Prerequisites', lines: 5 },
  { value: '04-quick-start', depth: 2, label: 'Quick Start', lines: 20 },
  { value: '04-commands', depth: 2, label: 'Core Commands', lines: 15 },
  { value: '04-troubleshooting', depth: 2, label: 'Troubleshooting', lines: 12 },
]

export const WithCollapsible = () => {
  const contentRef = useRef<HTMLElement | null>(null)

  return (
    <Toc.Root className={styles.Root} data-stacked items={items} scrollEl={() => contentRef.current}>
      <Collapsible.Root className={CollapsibleStyles.Root} style={{ width: '100%' }}>
        <Toc.Context>
          {({ activeItems }) => {
            const activeIndex = items.findIndex((i) => i.value === activeItems[0]?.value)
            const activeLabel = items[activeIndex]?.label ?? 'On this page'

            return (
              <Collapsible.Trigger className={CollapsibleStyles.Trigger}>
                <span className={styles.TriggerContent}>
                  <Ring index={activeIndex} total={items.length} />
                  <span key={activeLabel} className={styles.TriggerLabel}>
                    {activeLabel}
                  </span>
                </span>
                <Collapsible.Indicator className={CollapsibleStyles.Indicator}>
                  <ChevronRightIcon />
                </Collapsible.Indicator>
              </Collapsible.Trigger>
            )
          }}
        </Toc.Context>
        <Collapsible.Content className={CollapsibleStyles.Content}>
          <Toc.List className={styles.List}>
            {items.map((item, index) => (
              <Toc.Item className={styles.Item} key={item.value} item={item}>
                <Toc.Link className={styles.LinkNumbered} href={`#${item.value}`}>
                  <span className={styles.Number}>{String(index + 1).padStart(2, '0')}</span>
                  {item.label}
                </Toc.Link>
              </Toc.Item>
            ))}
          </Toc.List>
        </Collapsible.Content>
      </Collapsible.Root>

      <Toc.Content className={styles.Content} ref={contentRef}>
        {items.map((item) => (
          <section key={item.value}>
            <h2 id={item.value} className={styles.Heading} data-depth={item.depth}>
              {item.label}
            </h2>
            <div className={styles.DummyText}>
              {Array.from({ length: item.lines }).map((_, i) => (
                <div key={i} className={styles.DummyLine} />
              ))}
            </div>
          </section>
        ))}
      </Toc.Content>
    </Toc.Root>
  )
}

const Ring = ({ index, total }: { index: number; total: number }) => {
  const progress = index >= 0 ? (index + 1) / total : 0
  return (
    <svg width="28" height="28" viewBox="0 0 36 36" aria-hidden="true" className={styles.ProgressRing}>
      <circle cx="18" cy="18" r="14" fill="none" stroke="currentColor" strokeOpacity="0.2" strokeWidth="2.5" />
      <circle
        cx="18"
        cy="18"
        r="14"
        fill="none"
        pathLength="100"
        stroke="var(--demo-coral-solid)"
        strokeWidth="2.5"
        strokeDasharray={`${progress * 100} 100`}
        strokeLinecap="round"
        transform="rotate(-90 18 18)"
        style={{ transition: 'stroke-dasharray 0.4s ease-out' }}
      />
      <text
        key={index}
        x="18"
        y="18"
        textAnchor="middle"
        dominantBaseline="central"
        fontSize="10"
        fontWeight="600"
        fill="currentColor"
        className={styles.ProgressIndexText}
      >
        {index >= 0 ? index + 1 : '—'}
      </text>
    </svg>
  )
}

호버와 함께 (With Hover)

onMouseEnter에서 탐색을 펼치고 onMouseLeave에서 접으며, 핀 토글(pin toggle)로 열어 둘 수 있습니다.

참고: 호버는 터치 스크린에는 존재하지 않습니다. 핀 버튼이나 디스클로저(disclosure) 컨트롤과 함께 사용하여 모바일에서도 탐색이 가능하도록 하세요.

import { Swap } from '@ark-ui/react/swap'
import { Toc } from '@ark-ui/react/toc'
import { useRef, useState } from 'react'
import styles from 'styles/toc.module.css'

const items = [
  { value: '05-analytics-dashboard', depth: 2, label: 'Real-time Analytics', lines: 55 },
  { value: '05-cloud-storage', depth: 2, label: 'S3 Cloud Storage', lines: 14 },
  { value: '05-automation-tools', depth: 2, label: 'Workflow Automation', lines: 32 },
  { value: '05-crm-integration', depth: 2, label: 'Salesforce Sync', lines: 45 },
  { value: '05-report-generator', depth: 2, label: 'Custom PDF Reports', lines: 20 },
]

export const WithHover = () => {
  const [hovered, setHovered] = useState(false)
  const contentRef = useRef<HTMLElement | null>(null)

  return (
    <Toc.Root className={`${styles.Root} ${styles.HoverRoot}`} items={items} scrollEl={() => contentRef.current}>
      <Toc.Content className={styles.Content} ref={contentRef}>
        {items.map((item) => (
          <section key={item.value}>
            <h2 id={item.value} className={styles.Heading} data-depth={item.depth}>
              {item.label}
            </h2>
            <div className={styles.DummyText}>
              {Array.from({ length: item.lines }).map((_, i) => (
                <div key={i} className={styles.DummyLine} />
              ))}
            </div>
          </section>
        ))}
      </Toc.Content>
      <Toc.Nav
        className={styles.NavHover}
        data-expanded={hovered || undefined}
        onMouseEnter={() => setHovered(true)}
        onMouseLeave={() => setHovered(false)}
      >
        <Swap.Root className={styles.HoverSwap} swap={hovered}>
          <Swap.Indicator type="off" className={styles.HoverSkeleton}>
            {items.map((item) => (
              <Toc.Item item={item} key={item.value} className={styles.SkeletonBar} />
            ))}
          </Swap.Indicator>
          <Swap.Indicator type="on" className={styles.HoverList}>
            {items.map((item) => (
              <Toc.Item key={item.value} item={item} className={styles.Item}>
                <Toc.Link className={styles.HoverLink} href={`#${item.value}`}>
                  {item.label}
                </Toc.Link>
              </Toc.Item>
            ))}
          </Swap.Indicator>
        </Swap.Root>
      </Toc.Nav>
    </Toc.Root>
  )
}

인디케이터와 함께 (With Indicator)

Toc.List 안에 Toc.Indicator를 추가하면 활성 항목으로 슬라이드되는 마커를 제공합니다.

import { Toc } from '@ark-ui/react/toc'
import styles from 'styles/toc.module.css'
import { useRef } from 'react'

const items = [
  { value: '06-step-validation', depth: 2, label: 'Validation Pending', lines: 5 },
  { value: '06-upload-progress', depth: 2, label: 'Asset Uploading', lines: 90 },
  { value: '06-deployment-sync', depth: 2, label: 'Server Sync Active', lines: 12 },
  { value: '06-build-pipeline', depth: 2, label: 'CI/CD Running', lines: 105 },
  { value: '06-database-health', depth: 2, label: 'DB Connection Stable', lines: 3 },
]

export const WithIndicator = () => {
  const contentRef = useRef<HTMLElement | null>(null)

  return (
    <Toc.Root className={styles.Root} items={items} scrollEl={() => contentRef.current}>
      <Toc.Content className={styles.Content} ref={contentRef}>
        {items.map((item) => (
          <section key={item.value}>
            <h2 id={item.value} className={styles.Heading} data-depth={item.depth}>
              {item.label}
            </h2>
            <div className={styles.DummyText}>
              {Array.from({ length: item.lines }).map((_, i) => (
                <div key={i} className={styles.DummyLine} />
              ))}
            </div>
          </section>
        ))}
      </Toc.Content>

      <Toc.Nav className={styles.Nav}>
        <Toc.Title className={styles.Title}>On this page</Toc.Title>
        <Toc.List className={styles.List}>
          <Toc.Indicator className={styles.Indicator} />
          {items.map((item) => (
            <Toc.Item className={styles.Item} key={item.value} item={item}>
              <Toc.Link className={styles.Link} href={`#${item.value}`}>
                {item.label}
              </Toc.Link>
            </Toc.Item>
          ))}
        </Toc.List>
      </Toc.Nav>
    </Toc.Root>
  )
}

레일과 함께 (With Rail)

각 항목에 depth만큼 작은 SVG 오프셋을 부여하세요. 인접한 항목들이 서로 다른 depth에 있을 때, 베지어(bezier) 곡선이 두 위치를 연결하여 레일이 끊기지 않고 단계적으로 이어지도록 합니다.

import { Toc } from '@ark-ui/react/toc'
import { useRef } from 'react'
import styles from 'styles/toc.module.css'

const items = [
  { value: '07-overview', depth: 2, label: 'Overview', lines: 10 },
  { value: '07-installation', depth: 2, label: 'Installation', lines: 8 },
  { value: '07-package-manager', depth: 3, label: 'Package Manager', lines: 12 },
  { value: '07-peer-dependencies', depth: 3, label: 'Peer Dependencies', lines: 6 },
  { value: '07-usage', depth: 2, label: 'Usage', lines: 14 },
  { value: '07-server-components', depth: 3, label: 'Server Components', lines: 9 },
  { value: '07-styling', depth: 3, label: 'Styling', lines: 11 },
  { value: '07-theming', depth: 4, label: 'Theming', lines: 7 },
  { value: '07-api-reference', depth: 2, label: 'API Reference', lines: 12 },
]

// h2 sits at level 0; deeper headings step in, clamped so h5+ share h4's indent
const BASE = 8
const RAIL_STEP = 8
const TEXT_STEP = 12
const MAX_LEVEL = 2

// the rail overlaps the row above by BRIDGE px so the turn can straddle the boundary
const BRIDGE = 6

const levelOf = (depth: number) => Math.min(Math.max(depth - 2, 0), MAX_LEVEL)
const lineOffset = (depth: number) => BASE + levelOf(depth) * RAIL_STEP
const textOffset = (depth: number) => BASE + (levelOf(depth) + 1) * TEXT_STEP

const Rail = (props: { depth: number; prevDepth?: number; nextDepth?: number }) => {
  const { depth, prevDepth = depth, nextDepth = depth } = props
  const line = lineOffset(depth)
  const prevLine = lineOffset(prevDepth)
  const nextLine = lineOffset(nextDepth)
  const turns = prevLine !== line

  return (
    <svg
      className={styles.RailSvg}
      style={{
        top: -BRIDGE,
        width: Math.max(prevLine, line) + 9,
        height: line === nextLine ? `calc(100% + ${BRIDGE}px)` : '100%',
      }}
      aria-hidden="true"
    >
      {turns && (
        <path
          d={`M ${prevLine + 0.5} 0 C ${prevLine + 0.5} 8 ${line + 0.5} 4 ${line + 0.5} ${BRIDGE * 2}`}
          fill="none"
        />
      )}
      <line x1={line + 0.5} y1={turns ? BRIDGE * 2 : BRIDGE} x2={line + 0.5} y2="100%" />
    </svg>
  )
}

export const WithRail = () => {
  const contentRef = useRef<HTMLElement | null>(null)

  return (
    <Toc.Root className={styles.Root} items={items} scrollEl={() => contentRef.current}>
      <Toc.Content className={styles.Content} ref={contentRef}>
        {items.map((item) => (
          <section key={item.value}>
            <h2 id={item.value} className={styles.Heading} data-depth={item.depth}>
              {item.label}
            </h2>
            <div className={styles.DummyText}>
              {Array.from({ length: item.lines }).map((_, i) => (
                <div key={i} className={styles.DummyLine} />
              ))}
            </div>
          </section>
        ))}
      </Toc.Content>

      <Toc.Nav className={styles.Nav}>
        <Toc.Title className={styles.Title}>On this page</Toc.Title>
        <Toc.List className={styles.RailList}>
          {items.map((item, index) => (
            <Toc.Item className={styles.RailItem} key={item.value} item={item}>
              <Toc.Link
                className={styles.RailLink}
                href={`#${item.value}`}
                style={{ paddingInlineStart: textOffset(item.depth) }}
              >
                <Rail depth={item.depth} prevDepth={items[index - 1]?.depth} nextDepth={items[index + 1]?.depth} />
                {item.label}
              </Toc.Link>
            </Toc.Item>
          ))}
        </Toc.List>
      </Toc.Nav>
    </Toc.Root>
  )
}

트리 뷰와 함께 (With Tree View)

Toc.Root를 TreeView와 함께 사용하여 계층적 탐색을 구현하세요. onActiveChange는 활성 제목을 포함하는 브랜치를 펼칩니다.

import { Toc, useTocContext } from '@ark-ui/react/toc'
import { TreeView, createTreeCollection } from '@ark-ui/react/tree-view'
import { ChevronRightIcon } from 'lucide-react'
import { useState, useRef } from 'react'
import tocStyles from 'styles/toc.module.css'
import treeStyles from 'styles/tree-view.module.css'

type TocNode = {
  id: string
  name: string
  depth: number
  lines: number
  children?: TocNode[]
}

const sections: TocNode[] = [
  {
    id: '09-guides',
    name: 'Guides',
    depth: 2,
    lines: 10,
    children: [
      { id: '09-quick-start', name: 'Quick Start', depth: 3, lines: 6 },
      { id: '09-manual-setup', name: 'Manual Setup', depth: 3, lines: 5 },
    ],
  },
  {
    id: '09-core-concepts',
    name: 'Core Concepts',
    depth: 2,
    lines: 9,
    children: [
      { id: '09-toc-props', name: 'Props', depth: 3, lines: 7 },
      { id: '09-toc-events', name: 'Events', depth: 3, lines: 6 },
      { id: '09-toc-context', name: 'Context', depth: 3, lines: 8 },
    ],
  },
  {
    id: '09-advanced',
    name: 'Advanced',
    depth: 2,
    lines: 11,
    children: [
      { id: '09-root-api', name: 'Root Provider', depth: 3, lines: 7 },
      { id: '09-custom-rendering', name: 'Custom Rendering', depth: 3, lines: 6 },
    ],
  },
]

const collection = createTreeCollection<TocNode>({
  nodeToValue: (node) => node.id,
  nodeToString: (node) => node.name,
  rootNode: { id: 'ROOT', name: '', depth: 0, lines: 0, children: sections },
})

const allItems = sections.flatMap((section) => [
  { value: section.id, depth: section.depth },
  ...(section.children ?? []).map((child) => ({ value: child.id, depth: child.depth })),
])

const TocTreeNode = ({ node, indexPath }: TreeView.NodeProviderProps<TocNode>) => {
  const toc = useTocContext()
  return (
    <TreeView.NodeProvider node={node} indexPath={indexPath}>
      {node.children ? (
        <TreeView.Branch className={treeStyles.Branch}>
          <TreeView.BranchControl className={treeStyles.BranchControl}>
            <TreeView.BranchIndicator className={treeStyles.BranchIndicator}>
              <ChevronRightIcon />
            </TreeView.BranchIndicator>
            <TreeView.BranchText className={treeStyles.BranchText}>
              <a className={tocStyles.TreeLink} {...toc.getLinkProps({ item: { value: node.id, depth: node.depth } })}>
                {node.name}
              </a>
            </TreeView.BranchText>
          </TreeView.BranchControl>
          <TreeView.BranchContent className={treeStyles.BranchContent}>
            <TreeView.BranchIndentGuide className={treeStyles.BranchIndentGuide} />
            {node.children.map((child, index) => (
              <TocTreeNode key={child.id} node={child} indexPath={[...indexPath, index]} />
            ))}
          </TreeView.BranchContent>
        </TreeView.Branch>
      ) : (
        <TreeView.Item className={treeStyles.Item}>
          <TreeView.ItemText className={treeStyles.ItemText}>
            <a className={tocStyles.TreeLink} {...toc.getLinkProps({ item: { value: node.id, depth: node.depth } })}>
              {node.name}
            </a>
          </TreeView.ItemText>
        </TreeView.Item>
      )}
    </TreeView.NodeProvider>
  )
}

export const WithTreeView = () => {
  const [expandedValue, setExpandedValue] = useState<string[]>([])
  const contentRef = useRef<HTMLElement | null>(null)

  return (
    <Toc.Root
      className={tocStyles.Root}
      items={allItems}
      scrollEl={() => contentRef.current}
      onActiveChange={({ activeItems }) => {
        const activeIds = new Set(activeItems.map((i) => i.value))
        const next = sections
          .filter(
            (section) => activeIds.has(section.id) || (section.children ?? []).some((child) => activeIds.has(child.id)),
          )
          .map((s) => s.id)
        setExpandedValue(next)
      }}
    >
      <Toc.Content className={tocStyles.Content} ref={contentRef}>
        {sections.map((section) => (
          <section key={section.id}>
            <h2 id={section.id} className={tocStyles.Heading} data-depth={section.depth}>
              {section.name}
            </h2>
            <div className={tocStyles.DummyText}>
              {Array.from({ length: section.lines ?? 5 }, (_, i) => (
                <div key={i} className={tocStyles.DummyLine} />
              ))}
            </div>
            {section.children?.map((child) => (
              <div key={child.id}>
                <h3 id={child.id} className={tocStyles.Heading} data-depth={child.depth}>
                  {child.name}
                </h3>
                <div className={tocStyles.DummyText}>
                  {Array.from({ length: child.lines ?? 3 }, (_, i) => (
                    <div key={i} className={tocStyles.DummyLine} />
                  ))}
                </div>
              </div>
            ))}
          </section>
        ))}
      </Toc.Content>

      <Toc.Nav className={tocStyles.Nav}>
        <Toc.Title className={tocStyles.Title}>On this page</Toc.Title>
        <TreeView.Root
          className={treeStyles.Root}
          collection={collection}
          expandedValue={expandedValue}
          onExpandedChange={({ expandedValue: next }) => setExpandedValue(next)}
        >
          <TreeView.Tree className={treeStyles.Tree}>
            {sections.map((node, index) => (
              <TocTreeNode key={node.id} node={node} indexPath={[index]} />
            ))}
          </TreeView.Tree>
        </TreeView.Root>
      </Toc.Nav>
    </Toc.Root>
  )
}

가이드 (Guides)

항목 (Items)

모든 항목에는 제목 요소의 id인 value와 제목 수준인 depth가 필요합니다.

const items = [
  { value: 'introduction', depth: 2 },
  { value: 'installation', depth: 2 },
  { value: 'peer-dependencies', depth: 3 },
]

value는 제목의 id와 정확히 일치해야 합니다. 컴포넌트는 getElementById로 이를 resolve하여 가시성을 추적하고, Toc.Link는 href="#introduction"으로 이를 대상으로 합니다. id가 누락된 항목은 렌더링되지만 활성화되지는 않습니다.

id는 페이지에 전역적이므로, 한 페이지에 목차가 두 개 이상 있을 때는 접두사를 붙이세요.

추가 속성은 괜찮으며, 링크 텍스트용 label이 일반적입니다. TocItemData는 value와 depth만 다루므로, 직접 주석을 달기보다는 확장하세요:

import type { TocItemData } from '@ark-ui/react/toc'

interface Item extends TocItemData {
  label: string
}

API 참조 (API Reference)

Props

Root

Props

items Type: TocItem[] Required: true Default Value: undefined Description: value(slug/id)와 depth(제목 수준)를 가진 목차 항목들입니다.

activeIds Type: string[] Required: false Default Value: undefined Description: 제어(controlled)되는 활성 제목 id입니다.

asChild Type: boolean Required: false Default Value: undefined Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하며, 해당 요소의 props와 동작을 결합합니다.

autoScroll Type: boolean Required: false Default Value: true Description: 활성 제목이 변경될 때 첫 번째 활성 항목이 표시되도록 목차 컨테이너를 자동 스크롤할지 여부입니다.

defaultActiveIds Type: string[] Required: false Default Value: undefined Description: 렌더링 시 기본 활성 제목 id입니다. 활성 제목을 직접 제어할 필요가 없을 때 사용합니다.

id Type: string Required: false Default Value: undefined Description: 머신(machine)의 고유 식별자입니다.

ids Type: Partial<{ root: string title: string list: string item: (value: string) => string link: (value: string) => string indicator: string }> Required: false Default Value: undefined Description: 목차 내 요소들의 id입니다. 구성(composition)에 유용합니다.

onActiveChange Type: (details: ActiveChangeDetails) => void Required: false Default Value: undefined Description: 활성(보이는) 제목이 변경될 때 호출되는 콜백입니다.

rootMargin Type: string Required: false Default Value: "-20px 0px -40% 0px" Description: IntersectionObserver의 root margin입니다. 활성 제목을 결정하는 유효한 뷰포트 영역을 제어합니다.

scrollBehavior Type: ScrollBehavior Required: false Default Value: "smooth" Description: 목차 컨테이너를 자동 스크롤할 때와 제목으로 스크롤할 때(링크 클릭 또는 api.scrollTo) 사용되는 기본 스크롤 동작입니다. api.scrollTo에 behavior를 전달하여 호출별로 재정의할 수 있습니다.

scrollEl Type: () => HTMLElement | null Required: false Default Value: undefined Description: 관찰할 스크롤 컨테이너 요소를 반환하는 함수입니다. 기본값은 문서/뷰포트입니다.

threshold Type: number | number[] Required: false Default Value: 0 Description: IntersectionObserver의 threshold입니다. 값 0은 root margin 영역 안에 1픽셀만 보여도 해당 제목이 활성화됨을 의미합니다.

Content

Props

asChild Type: boolean Required: false Default Value: undefined Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하며, 해당 요소의 props와 동작을 결합합니다.

Indicator

Props

asChild Type: boolean Required: false Default Value: undefined Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하며, 해당 요소의 props와 동작을 결합합니다.

Item

Props

item Type: TocItem Required: true Default Value: undefined Description: 목차 항목입니다.

asChild Type: boolean Required: false Default Value: undefined Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하며, 해당 요소의 props와 동작을 결합합니다.

데이터 속성 (Data Attributes)

data-scope: toc data-part: item data-value: 항목의 값입니다. data-depth: 항목의 depth입니다. data-active: 활성화되거나 눌렸을 때 표시됩니다. data-first: data-last:

Props

asChild Type: boolean Required: false Default Value: undefined Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하며, 해당 요소의 props와 동작을 결합합니다.

데이터 속성 (Data Attributes)

data-scope: toc data-part: link data-value: 항목의 값입니다. data-active: 활성화되거나 눌렸을 때 표시됩니다.

List

Props

asChild Type: boolean Required: false Default Value: undefined Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하며, 해당 요소의 props와 동작을 결합합니다.

Props

asChild Type: boolean Required: false Default Value: undefined Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하며, 해당 요소의 props와 동작을 결합합니다.

placement Type: 'left' | 'right' Required: false Default Value: undefined Description: undefined

RootProvider

Props

value Type: UseTocReturn Required: true Default Value: undefined Description: undefined

asChild Type: boolean Required: false Default Value: undefined Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하며, 해당 요소의 props와 동작을 결합합니다.

Title

Props

asChild Type: boolean Required: false Default Value: undefined Description: 제공된 자식 요소를 기본 렌더링 요소로 사용하며, 해당 요소의 props와 동작을 결합합니다.

Context

API:

Property Type Description
activeIds string[] 현재 활성(보이는) 모든 제목 id입니다.
activeItems TocItem[] 활성(보이는) 목차 항목들입니다.
items TocItem[] resolve된 항목 목록입니다.
setActiveIds (value: string[]) => void 활성 제목 id를 수동으로 설정합니다.
scrollTo `(value: string, details?: ScrollToDetails undefined) => void`
getItemState (props: ItemProps) => ItemState 목차 항목의 상태를 반환합니다.

더 알아보기 (Learn more)