Table of Contents

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



    {tableOfContents.map((item) => (

  • <a href={#${item.id}}>{item.title}

  • ))}

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

1 Like

Hi, does your heading block tsx also uses id property as id html attribute? If yes, then you good to go!

for example:
export const HeadingBlock = (props) => {
const { id, title } = props;

return (

{title}


);
};

1 Like