Table of Contents
The TableOfContents
components scans the article
-section of a page for all h2, h3 and h4 headings and presents a table of contents as an accordion
component that contains clickable links to those headings. In this demo site it is being used in the aside
-section of the page
(depending on device and posture, either shown above or on the right side (or left, depending on LTR choice) of the article
-section).
The component uses the id attributes of the headings it finds to create the bookmarks. If a heading doesn't have an id attribute set, the JavaScript will create one based on the title of the heading.
The component also renders a (initially hidden) 'Back to top' button at the bottom of the page. The button appears once scrolling has started. It works on either scrolling of the 'body' element or on schrolling of an element with the id 'body-content' in case of a setup with partial parts of the screen scrollable (as here in the demo site).
Making TableOfContents
component aware of new headings
When using this component in combination with other components that update the DOM with new headings (like the MarkdownSection
component),
the TableOfContents
component needs to be made aware of these new headings. To do this you need to take the following steps:
- Create a reference to the
TableOfContents
component - Create an
EventCallback
and handler in the code of the main layout of the site - Cascade the
EventCallback
down in the @Body parameter - Add code to pages that alter the DOM so the cascaded event gets raised
The following code snippets show how this is done in this demo site.
Create a reference to the TableOfContents
component
In DemoMainLayout.razor
:
<TableOfContents @ref=_toc />
@code {
private TableOfContents? _toc;
}
Create EventCallback
and handler
In DemoMainLayout.razor.cs
:
public EventCallback OnRefreshTableOfContents => EventCallback.Factory.Create(this, RefreshTableOfContents);
private async Task RefreshTableOfContents()
{
await _toc!.Refresh();
}
Cascade event in DemoMainLayout.razor
In DemoMainLayout.razor
:
<CascadingValue Value=@OnRefreshTableOfContents>
@Body
</CascadingValue>
Add event handling to pages that alter the DOM
For example inCodeSetup.razor
we call the MarkdownSection
component which
adds content to the page that contains headings:
@page "/CodeSetup"
<MarkdownSection FromAsset="./_content/FluentUI.Demo.Shared/docs/CodeSetup.md" OnContentConverted="RefreshTableOfContents" />
@code {
[CascadingParameter]
public EventCallback OnRefreshTableOfContents { get; set; }
private async Task RefreshTableOfContents()
{
await OnRefreshTableOfContents.InvokeAsync();
}
}
Example
Default
Documentation
TableOfContents Class
Parameters
Name | Type | Default | Description |
---|---|---|---|
ChildContent | RenderFragment? | ||
Heading | string | In this article | |
ShowBackButton | bool | True |
Methods
Name | Parameters | Type | Description |
---|---|---|---|
Refresh | Task |