Ben
Ben

Reputation: 16689

Scroll to element when clicking table of contents

In React, how can I scroll to a heading on the page, when the corresponding heading is clicked in my table of contents?

  1. I parse my markdown document to generate a TOC:
const toc = [
    {    id: 'lorem',    title: 'Lorem'    },
    {    id: 'ipsum',    title: 'Ipsum'    },
    {    id: 'dolor',    title: 'Dolor'    }
];
  1. I then render this TOC in render()::
{ toc.map((entry) => {
return (
    <li key={entry.id}>
        {entry.title}
    </li>
);
})}
  1. When I click on an entry in my TOC, I would like the page to scroll to the h2 element with that id. How?

The examples I have seen all use ref. But I am not sure how to use ref in my case, where the TOC is created dynamically at runtime and hence the refs would need to be created dynamically? I cannot add them to my document's elements, since they are generated by markdown-to-jsx.

Upvotes: 0

Views: 1116

Answers (1)

Ali Mousavi
Ali Mousavi

Reputation: 915

You need to add IDs to your Markdown headers in your Markdown files and you can add IDs with this syntax:

### Lorem {#lorem}

Then in your React code you render the TOCs with link tag linking to header IDs:

{ toc.map((entry) => {
return (
    <li key={entry.id}>
        <a href={`#${entry.id}`}>{entry.title}</a>
    </li>
);
})}

To read more about Markdown ID syntax: https://www.markdownguide.org/extended-syntax/#heading-ids

Upvotes: 2

Related Questions