Syntax Highlight Code in NextJS TailwindCSS DaisyUI
Code syntax highlighting is needed to make code more readable and understandable. In this article, you will learn how to implement syntax highlighting in your Next.js website using TailwindCSS, DaisyUI, react-markdown, react-syntax-highlighter, and more.
I have created a simple repository for this tutorial. You can check it out to better understand how to implement this on your website. The link to the repository is provided in the full code section below.
Install Dependencies
To use syntax highlighting, we need to install the following dependencies:
npm i react-copy-to-clipboard react-syntax-highlighter
For development dependencies, we need to install:
npm i -D @heroicons/react @types/react-copy-to-clipboard @types/react-syntax-highlighter daisyui tailwind-scrollbar
Add code components in your ReactMarkdown
Wrap your Markdown string with the <ReactMarkdown> component for rendering. It should look like this:
Find your ReactMarkdown component or create a new component and pass the Markdown string to it.
In this ReactMarkdown component, we will add the react-syntax-highlighter to highlight our code.
Adding SyntaxHighlighter to the ReactMarkdown
In the ReactMarkdown component, we can style our HTML tags by passing props to our code component. Update the code component with the following code snippet:
In this code, we are using TailwindCSS, DaisyUI, and tailwind-scrollbar to style the code block. It will now look like this:
When running npm run dev:
When running npm run build:
However, there is a problem with the code highlighting in npm run build. To fix this, we need to register the syntax highlighter languages in our MarkdownRender component file.
Register Language for SyntaxHighlighter
We can register languages using the registerLanguage method provided by SyntaxHighlighter. Below, I have added some popular languages, but you can add more languages. Here is the list of supported languages by Prism. Check here for the languages supported by Prism.
Add the following lines of code in the MarkdownRender component file:
A copy code button will allow readers to quickly copy code snippets to their clipboard. This button is highly useful. Additionally, displaying the language name will help in better understanding the code.
To achieve this, we need to update the pre HTML tag in the code.
Here is the pre code for the MarkdownRender component:
You can also see the, this website implementation of this code syntax highlighter on the PNP project, which is an open-source project. Here is the link to the PNP GitHub repository below -