I am trying to create a table of contents for my blog. I’ve created this function:
function generateTableOfContents(content: BlocksContent) {
const toc: { id: string; title: string } = ;
content.forEach((block: any, index: number) => {
if (block.type === 'heading' && (block.level === 1 || block.level === 2 || block.level === 3)) {
const id = `heading-${index}`;
const title = block.children[0]?.text || `Heading ${index + 1}`;
toc.push({ id, title });
block.id = id; // Assign id to the heading for anchor linking
}
});
return toc;
}
And then display the the content like this:
Table of Contents
<a href={#${item.id}
}>{item.title}
{tableOfContents.map((item) => (
))}
but i have no idea how i would be able to inject the ids into the H1/H2 etc for quick anchor linking
This topic has been created from a Discord post (1274006195539283999) to give it more visibility.
It will be on Read-Only mode here.
Join the conversation on Discord