challenges

MDX Table of Contents: Part 5

Workshop context

  • In the previous four workshops, you created and displayed a table of contents from the MDX blog headings, and added an id for each heading.
  • In the remaining future workshop, you’ll refine the scroll for position and smooth scrolling.

Workshop goal

By the end of this workshop:

  • Clicking on a heading in the table of contents should scroll the blog content so that heading is at the top of the viewport.

Notes:

  1. After this workshop, the heading will scroll to the top of the viewport, and will be hidden under the header. That will be resolved in the next workshop.
  2. After this workshop, the heading will jump to the top of the screen instead of scrolling with a smooth animation. This will also be resolved in the next workshop.

Hints

Hint 1 Use the headingToId function written in the last workshop to generate the id for the link. You can call headingToId from within extractMdxHeadings and add the id to the HeadingData object pushed to the headings array. You’ll have to update the typescript for HeadingData to include a id property with a string type. All of this takes place in the headings-helpers.ts file.

Hint 2 You will need to update headingToId to remove underscores (_), which are used for italics in Markdown . The current headingToId doesn’t remove them, because they’re included in the \w character class .

Hint 3 Destructure the id when mapping over the extractMexHeadings return value in ToC.tsx, similar to how title and level are already destructured.

Hint 4 You can link to the position of an id on the same page – see this MDN documentation .

Resources