Skip to content

Instantly share code, notes, and snippets.

@khasky
Created April 8, 2026 06:40
Show Gist options
  • Select an option

  • Save khasky/943bb1a3a77b6884e33158a26bb20efd to your computer and use it in GitHub Desktop.

Select an option

Save khasky/943bb1a3a77b6884e33158a26bb20efd to your computer and use it in GitHub Desktop.
useHeadingAnchors React Hook
// 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