Add Custom Code Block/highlighter to nextJs

Seriously, guys, I need your help!

I was going through Prismic's blog a while ago, and I noticed they have code samples well highlighted on their blog posts. For example, this post is well highlighted with code samples. I have been looking for ways to add code highlighter to my newly created blog but not really working.

I need a way to get that done ASAP so that I can start writing really good articles. Please!

Hi @chadereiroro134,

I believe that the Prismic blog uses the Shikiji library for its code formatting. Beyond that, I don't know how it's implemented.

That said, I work on Primsic's documentation website, and can show you how we've set up our code snippet formatting using the highlight.js library. It's pretty simple to use. Here's a very basic example of a react component:

import React from 'react'
import * as prismic from '@prismicio/client'
import hljs from 'highlight.js'

export default function CodeBlock({ snippetField }) {
  const unhighlightedCode = prismic.asText(snippetField)
  const highlightedCode = hljs.highlightAuto(unhighlightedCode)

  return (
      <code dangerouslySetInnerHTML={{ __html: highlightedCode }} />

You'll also have to add the highlight.css file to your website, but you can follow the library's instructions to get all the pieces in place.

In this case, snippetField is a rich text field in Prismic. I usually set the configuration for this to only allow "preformatted" and "allow multiple lines".

From here, there are more customizations you can do with highlight.js, but hopefully, this gets you going on the right path.


1 Like

Thank you Levi for the response.

I will definitely try to implement this! I'm currently not at home now, when I get home I'd give this a shot!!!

Thank you once again!

1 Like