Back to Blog

Syntax Highlighting with Prism

When displaying code on a website, it is common practice to use syntax highlighting to make the code look better for readers. Syntax highlighting is the process by which words and operators are colored in specific ways, making the code more readable and adding style to the site. Here's an example of a JavaScript function displayed with syntax highlighting:

function hello() {
  console.log('Hello world.');
}

Prism is a lightweight tool web developers can use to add syntax highlighting to their websites. Prism is easy to use and allows for a variety of color options as well as other useful features all in a small JavaScript package. This guide will show examples of using Prism with Create React App and Next.js.


Using Prism with Create React App

In this section we will assume the reader has a Create React App project that has already been created.

The first step to using Prism will be to visit their website here. You will need to download two files from their website: a prism.js file and a prism.css file. The prism.js file will contain the core along with any additional languages and plugins needed. The prism.css file will determine which colors are used in the end product. Styles can be previewed on the Prism homepage.

After you have downloaded the JavaScript and CSS files from the Prism website, they will need to be added to the Create React App project. Both of these files can be placed directly into the public folder of the project.

With the prism.js and prism.css files in the public folder, the next step will be to link them. Go to the index.html file, also located in the public folder, and paste the following code into the head section:

<link rel="stylesheet" href="/prism.css" />
<script async src="%PUBLIC_URL%/prism.js"></script>

Finally, we will want to create a component that will handle the highlighting of code passed to it. This component can be used anywhere in your site to display highlighted code. The following is one example of how the component can be written:

import './CodeBlock.css'
import { useEffect, useRef } from 'react'

const CodeBlock = (props) => {
  const code = props.code
  const codeRef = useRef(null)


  useEffect(() => {
    if (codeRef.current) {
      window.Prism?.highlightElement(codeRef.current);
    }   
  })

  return (
    <div className='code-block-container'>
      <pre><code ref={codeRef} className='language-javascript'>{code}</code></pre>
    </div>
  )
}

export default CodeBlock

Any display code passed to <CodeBlock> will now be highlighted with the styles from the CSS file you downloaded. To change the styles, you can swap the CSS file for a different one from the Prism website.


Using Prism with Next.js

Setting up Prism in a Next.js project will require several different steps when compared to Create React App. There are multiple ways to get Prism working with Next.js, but this guide will follow the method currently being used on this blog.

For this guide, the reader should already have a Next.js project started. We will also be using MDX, a tool for writing JSX in Markdown files. To learn more about using MDX in Next.js, view this article.

There are two key pieces we will need to enable Prism in Next.js: a Prism CSS file, and a javascript package named remark-prism.

The CSS file can be downloaded from the Prism website here. This file can be added to the styles folder along with other CSS files for your Next.js project. It will then need to be imported into your _app.js file with this line:

import '../styles/prism-theme.css'

To use the remark-prism package, it needs to be installed to your Next.js project. It can be installed with NPM using this command:

npm install remark-prism

With the package installed, the final step to get everything working is to require the package in the next.config.js file. Because we are using MDX, this will only require one line to be inserted in the remarkPlugins options. This is what the next.config.js will look like with MDX and Prism set up:

const withMDX = require('@next/mdx')({
  extension: /\.mdx?$/,
  options: {
    remarkPlugins: [require("remark-prism")],
    rehypePlugins: []
  }
})
 
module.exports = withMDX({
  pageExtensions: ['ts', 'tsx', 'js', 'jsx', 'md', 'mdx']
})

At this point, everything is set up properly to have automatic syntax highlighting in your MDX files. The code can be written like it normally would in Markdown, just remember to include the name of the language so Prism knows what to highlight.