CalvinTorra
Add Prism.js Code Highlighting to Next.js
IdontKnowJS

Grab The Guides

I was jealous of the blogs that had nice code blocks on their site and I wanted to add it to mine.

However I was having major issues with things like importing gists into React/Next because of the DOM rendering.

I believe that the page was rendered before the github scripts could run which left my code blocks looking funky and non functioning.

I had tried other packages that parsed my imported html, found code blocks and highlighted them but the code was so verbose it was just annoying.

Prism.js

I think i was snooping around the html on https://swizec.com/blog/ where I noticed something called Prism.js being used.

Turns out it’s a nice little package and here’s how to add it to your next.js site.

Installing the package

$ npm install prismjs

Import the CSS to _app.js

You can check out all the different language support and themes you add to your site here at Prism.js. I chose the tomorrow theme.

import "prismjs/themes/prism-tomorrow.css";

UseEffect async render

I was having issues with my static blog pages being rendered after Prism tried to style it which obviously didn’t work out :(.

So I stuck the function for prism rendering into a useEffect hook and updated it once my blog post props had been fetched and passed in.

Once the post had been passed in, I then wanted to wait for Prism to do it’s thing by using async await and Voila.

import Prism from "prismjs";
const Blog = ({ post }) => {
  useEffect(() => {
    const highlight = async () => {
      await Prism.highlightAll(); // <--- prepare Prism 
    };
    highlight(); // <--- call the async function
  }, [post]); // <--- run when post updates

Styling your code

Now everything you want to be highlighted needs to be wrapped in a pre and code tag with the language specified.

<pre><code class="language-XXXX">const userArray = [ "London", "Sydney", "Madrid", "Boston", "Verona", "Rome", "Athens", "Porto", "Meteora", ] </code></pre>

const userArray = [
    "London",
    "Sydney",
    "Madrid",
    "Boston",
    "Verona",
    "Rome",
    "Athens",
    "Porto",
    "Meteora",
  ];

Importing JSX Highlighting

Wherever you choose to import your Prism module, you'll also need to add...

import Prism from "prismjs";
import "prismjs/components/prism-jsx";

Grab The Guides

React Query
Redux Toolkit
React Testing Library
Contact Me