Created
April 8, 2026 06:40
-
-
Save khasky/943bb1a3a77b6884e33158a26bb20efd to your computer and use it in GitHub Desktop.
useHeadingAnchors React Hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // After mount, collects linked headings (`a > h2`–`h6`) into `{ id, text }` pairs | |
| // from the parent anchors `id`; state updates only when there are at least two (for TOC-style UI). | |
| import React from 'react'; | |
| export interface HeadingAnchor { | |
| id: string; | |
| text: string; | |
| } | |
| export const useHeadingAnchors = () => { | |
| const [headingAnchors, setHeadingAnchors] = React.useState<HeadingAnchor[]>([]); | |
| React.useEffect(() => { | |
| const headings: HeadingAnchor[] = []; | |
| const anchorElements = document.querySelectorAll('a h2, a h3, a h4, a h5, a h6'); | |
| anchorElements.forEach((anchor) => { | |
| const id = anchor?.parentElement?.getAttribute('id'); | |
| const text = anchor.textContent?.trim() || ''; | |
| if (id) { | |
| headings.push({ id, text }); | |
| } | |
| }); | |
| if (headings.length > 1) { | |
| setHeadingAnchors(headings); | |
| } | |
| }, []); | |
| return headingAnchors; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment