nextjs tailwindcss toc
Author Cloudapp
E.G.

Next.js 14 - Easy TOC creation and Code block highlight

April 29, 2024
Table of Contents

Structuring your content is great for both your users and search engines, but sometimes it leads to a lot of work for the authors/editors. Therefore, I want to show you a simple and automatic way to create a table of contents and highlight code blocks. This step-by-step guide will add three new components. We will use Contentful as the CMS, but you can use any CMS that provides JSON data.

The complete code is available in this GitHub repo.

Here's a spoiler for the finished website -> https://nextjs14-toc-codeblock-highlight-copy.vercel.app/testblogpost3

The link leads directly to the blog post "testblogpost3", which shows the changes made.

I will showcase how quickly and easily editors can automate certain parts of their work.

Here are all files that were created and/or modified.

Modified Files
Modified Files

Let’s start with the TOC Component ArticleToc.tsx. As you can see, the magic comes from TailwindCss and nothing else.

The next component is ArticleTocItem.tsx, which is quite simple and used for setting the Anchor-id. We need it to jump directly to the H2 if a user clicks on the corresponding entry in the TOC.

Both TOC components were then imported into CtfRichText.component.tsx, which is the main component used for visualizing the content on the front end.

In the code below, we set the Anchor-id with the ArticleTocItem component.

At the end of the CtfRichText.component.tsx we loop through the json.content to create an array, which we use to show our TOC at the beginning of the blog post.

Code Block highlight and Copy function

As you may have already seen, we also imported the CopyButton component into CtfRichText.component.tsx.

In the MARKS.CODE section, we use the component to highlight the code and to show the Copy button.

Component ArticleCodeCopy.tsx

In Contentful (RichTextField), we must format the content correctly so the trick works.

H2-Titles will be used for the TOC.

TOC open
TOC open

Code formatted text parts will be highlighted, and the copy button will appear.

Copy Button Screenshot
Copy Button Screenshot

As a last step, we add new translations to the common.json file for every language, and we are done.

It is straightforward and can be built with Tailwind in minutes.

Cloudapp-dev, and before you leave us

Thank you for reading until the end. Before you go:

  • Please consider clapping and following the writer! 👏 on our Medium Account

Related articles