component :: Table of Content
The .toc
component is an “Astro only” client-side rendered component. It creates a table of content from the headings on the page it’s on:
By default, the TOC includes H2
s and H3
s (customizable via props) that have an id
attribute and links to them.
It’s possible to add multiple TOC on the same page, but this will duplicate Javascript and it’s not recommended. If you do need to include more than one TOC, you’ll need to add a unique id
to each instance of the component.
File Name | class | Source |
---|---|---|
component.toc.css | .toc | Github |
HTML
This component’s main functionality is to create a table of content via JavaScript. It just renders a nested ul
and it’s most useful as an Astro component.
Custom properties
The following custom properties are available in the default theme:
Property | Color |
---|---|
--toc-color | Links color. |
--toc-color-hover | Links hover color. |
--toc-spacing | Links padding. |
--toc-icon-size | Icon size. |
--toc-indentation | Nested lists indentation. |
Astro component
Prop | Type | Default | Description |
---|---|---|---|
id | string | toc | Needed to add more than one TOC. |
selector | string | main | HTML element to scan for headings. |
headings | array | ['h2','h3'] | Heading levels to include. |
baseUrl | string | '' | Optional URL to prepend #id with. |
scrollOffset | integer | 0 | Scroll position offset from the top.. |
description | string | undefined | Text above the TOC. |
icon | string | '' | Optinal inline SVG. (See example.) |
extraClass | string | undefined | Additional CSS, useful for helper classes. |
Examples
TOC with only H2s
--- import Toc from "../../components/Toc.astro"; --- <Toc id="example2" selector=".docs" headings={["h2"]} scrollOffset={80} description={"Just H2s"} />
TOC with H2 — h4 and a ♥︎ icon
A H4 just as an example
--- import heart from "../../assets/icons/arrow-right-small.svg?raw"; import Toc from "../../components/Toc.astro"; --- <Toc id="example3" selector=".docs" headings={["h2", "h3", "h4"]} scrollOffset={80} icon={heart} />