Syntax highlighter in Next.js
In this post, we will go through the steps to integrate react-syntax-highlighter, a popular syntax highlighting library, into a Next.js project. This will allow you to highlight code snippets in your Next.js application.
Install 'react-syntax-highlighter'
Install the react-syntax-highlighter package
bash
1npm install react-syntax-highlighter
or
bash
1yarn add react-syntax-highlighter
Use 'react-syntax-highlighter' in a Component
Create a component that uses 'react-syntax-highlighter' to render some highlighted code. We will create a new component file called 'code.js'
/app/_components/code/code.js
1import SyntaxHighlighter from "react-syntax-highlighter";
2import { atomOneDark } from "react-syntax-highlighter/dist/esm/styles/hljs";
3import BtnCopy from "../btn/copy/copy";
4import styles from "./code.module.css";
5
6
7export default function CodeBlock(props) {
8 const regexLang = /(?<=(<pre><code\s+class="language-))\w+(?=")/;
9 const regexCodeString = /(?<=<pre><code.*>).+(?=(<\/code><\/pre>))/s;
10 const regexMDir = /(\*\-\-)(.*?)(\-\-\*)/g;
11 const regexDir = /(?<=(\*\-\-))(.*?)(?=(\-\-\*))/g;
12
13 //extract title
14 let title = props.codeString.match(regexDir)
15 ? props.codeString.match(regexDir)[0]
16 : "";
17 let content = props.codeString.replace(regexMDir, "");
18
19 if (title) {
20 content = content.replace("\n", "");
21 }
22
23 //extract lang
24 let lang = content.match(regexLang)?.[0];
25 if (lang === "plaintext") lang = "text";
26
27 const str = content
28 .match(regexCodeString)[0]
29 .replaceAll("<", "<")
30 .replaceAll(">", ">")
31 .replaceAll("&", "&");
32
33 return (
34 <section className={styles.pre}>
35 <div className={styles.header}>
36 <span>{title || lang}</span>
37 <BtnCopy text={str} color={"black"} />
38 </div>
39 <SyntaxHighlighter
40 language={lang}
41 style={atomOneDark}
42 showLineNumbers={true}
43 >
44 {str}
45 </SyntaxHighlighter>
46 </section>
47 );
48}
49