Workshop context
- In the previous three workshops, you created and displayed a table of contents from the MDX blog headings.
- In future workshops, you’ll add links from the table of contents headings that scroll to the corresponding heading in the post.
Workshop goal
By the end of this workshop:
- The HTML element for each heading in the blog content should have an id attribute . This attribute will eventually be used to identify where to scroll when the heading is clicked in the table of contents.
- This
id
value will end up in the URL after clicking the heading’s title in the table of contents (we’ll implement this in the next workshop). So theid
value should be (a) URL-friendly (that is, not contain characters that need to be encoded ), and (b) indicative of the heading title (instead of, say, a random number). Example of a goodid
value:effective-learning-techniques
. Examples of not-so-goodid
values:Why travel? It's fun!
(contains non-URL-friendly characters: spaces,?
,!
), or35234321251
(doesn’t indicate which heading the id is for).
Hints
Hint 1
There are two places in the app that will eventually need to create an ID from heading text:
- the
BlogHeading
component (where theid
attribute will be added to the heading). That’s this workshop. - 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
- react-to-text , a handy little utility to extract text from a React node
- String.prototype.replace
- Regular Expressions (again!)