Reputation: 16689
In React, how can I scroll to a heading on the page, when the corresponding heading is clicked in my table of contents?
const toc = [
{ id: 'lorem', title: 'Lorem' },
{ id: 'ipsum', title: 'Ipsum' },
{ id: 'dolor', title: 'Dolor' }
];
render()
::{ toc.map((entry) => {
return (
<li key={entry.id}>
{entry.title}
</li>
);
})}
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
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