Hrishikesh Pathak

Highlight code snippets in Nextjs

nextjs
reactjs
Highlight code snippets in Nextjs

Hi Developers, today we are going to see how to implement syntax highlighting in your ReactJS or nextjs site with the help of a prismJs based NPM package, called prism-react-renderer.

This tutorial will be helpful if you want to highlight a code block in your website. It has quite a few options of colour themes from which you can choose your favourite one.

What is the use of syntax highlighting

So before starting, let's discuss a little about what is syntax highlighting and why we need this.

In every modern code editor, we can see syntax highlighting in action. This increases the readability of the code and a developer can easily interpret what the code is all about.

Syntax highlight can save a lot of time if a developer needs to review code or skim through the code very quickly. We can compare it with a well-structured blog post with an appropriate header and subhead so that the reader can easily find their required information.

Implementing code blocks in a blog or a website is really important if the niche of the website is programming or coding. If you add syntax highlighting over it, the site feels really cool and plays an important role in the user experience.

How to implement syntax highlighting

Let's break down this meat part of the article into atomic blocks and try to follow them step by step.

1. Install required packages

Go to your project root directory where you have package.json file and run this command

1# npm
2npm install --save prism-react-renderer
3# yarn
4yarn add prism-react-renderer
5

2. Import the package into your .jsx file

first import Highlight component and defaultProps in your file.

1import Highlight, { defaultProps } from "prism-react-renderer";
2

3. Write your code snippets

Define your code snippets and assign this to a variable. Make sure to define the code with the required indentation. The code will be put inside a pre tag by the Highlight component so that indentation should be maintained.

1import Highlight, { defaultProps } from "prism-react-renderer";
2
3const exampleCode = `
4(function someDemo() {
5 var test = "Hello World!";
6 console.log(test);
7})();
8
9return () => <App />;
10`;
11

4. Configure Highlight component from Prism-react-renderer

You can define the language of the code inside the language parameter. e.g., language=python or language=js etc.

Then put your code snippets in the code parameter. In this case, we are referring to the exampleCode variable we have defined above.

You can do custom styling by appending your custom class inside the className attribute of <pre> tag.

1import Highlight, { defaultProps } from "prism-react-renderer";
2
3const exampleCode = `
4(function someDemo() {
5 var test = "Hello World!";
6 console.log(test);
7})();
8
9return () => <App />;
10`;
11
12const CodeBlock=()=>{
13 return (<Highlight {...defaultProps} code={exampleCode} language="jsx">
14 {({ className, style, tokens, getLineProps, getTokenProps }) => (
15// add your custom style by appending your className
16 <pre className={className ${your_custom_class}} style={style}>
17 {tokens.map((line, i) => (
18 <div {...getLineProps({ line, key: i })}>
19 {line.map((token, key) => (
20 <span {...getTokenProps({ token, key })} />
21 ))}
22 </div>
23 ))}
24 </pre>
25 )}
26 </Highlight>);
27

5. Use this as a component

If you are using ReactJS or NextJs then it makes no sense to repeat yourself over and over again to simply implement a code snippet. So instead of doing this, you can create a component that can accept two props. One is the formatted code itself and another one is the code language.

Then later we have to just pass those props and our job will become very easy. Let's implement this concept in code.

1import Highlight, { defaultProps } from "prism-react-renderer";
2
3const CodeBlock=({code,codelang})=>{
4 return (<Highlight {...defaultProps} code={code} language={codelang}>
5 {({ className, style, tokens, getLineProps, getTokenProps }) => (
6// add your custom style by appending your className
7 <pre className={className ${your_custom_class}} style={style}>
8 {tokens.map((line, i) => (
9 <div {...getLineProps({ line, key: i })}>
10 {line.map((token, key) => (
11 <span {...getTokenProps({ token, key })} />
12 ))}
13 </div>
14 ))}
15 </pre>
16 )}
17 </Highlight>);
18
19export default CodeBlock;
20

Now, let's use this CodeBlock component in other components.

1// Put your relative path and import CodeBlock from it
2import CodeBlock from "./CodeBlock"
3
4const OtherComponent=()=>{
5// Pass the code and codelang props
6 return <CodeBlock code=`console.log("Hello world")` codelang="js" />
7}
8

So this is it. I have done quite a little research to implement syntax highlighting in this blog. After a lot of trial and error, This method is working for me. You can see the live example in front of you.

If you like this post, share it or at least make a tweet about it. Don't forget to tag me. You can find me as @hrishikshpathak on Twitter.

Thanks for reading.