Writing a React Table of Contents Component

Eyas
6 min readMar 11, 2022

Last year, I wrote about migrating this blog to Next.js. It ended up being a huge post, so I wrote a<TOC> React component to make it more navigable.

The bulk of the logic for this component is based on Emma Goto’s great examples in her “ How to build a table of contents in React”, with a few improvements worth discussing. If you haven’t yet, go read that post! Emma does a great job showing both the final working solution and explaining the thinking behind it step-by-step.

In this post, I’ll give a brief tour of the few “interesting” areas I iterated on top of Emma’s work.

Computing Heading Structure

In my TOC component, we compute the heading structure dynamically at runtime based on the structure of the emitted HTML. While some tools can give you a nested representation of your headings for free, I decided against that.

Emma’s example used a getNestedHeadings function that took a HTMLElement array of<h2> and <h3> headings and returned a nested array representing the structure. The function decided this nesting manually, which is easy enough if you have content that isn't highly nested. But I wanted my blog to support nesting much deeper than that when needed, so I ended up writing something a bit different:

--

--

Eyas

Software Engineer living in Brooklyn, NY. MIT Computer Science S.B. ’13, M.Eng. ‘14. From Amman, Jordan. Interested in politics, current affairs, and technology