challenges

MDX Table of Contents: Part 4

Workshop context

Your goal

By the end of this workshop:

Hints

Hint 1 There are two places in the app that will eventually need to create an ID from heading text:

  1. the BlogHeading component (where the id attribute will be added to the heading). That’s this workshop.
  2. the ToC component (where the links will be added to each table of contents item). This will happen in the next workshop.

You may want to write a helper function that translates heading text into a heading id, so the same algorithm can be used in both places. src/helpers/headings-helpers.ts would be a good place for this function.

Hint 2 To get the heading text from within the BlogHeading component (src/components/BlogHeading/BlogHeading.tsx), use the react-to-text utility on the children prop.

Hint 3 Transform the text into something URL-friendly using replace and Regular Expressions . In my case I removed everything that wasn’t a word character (\w), a space character (\s) or a hyphen (-), and then replaced any space characters with a hyphen.

You might also consider using toLowerCase – it’s not necessary but (in my opinion) all lower case looks more uniform and orderly for the id.

Resources