DWE

Code blocks in Sanity

Cover Image for Code blocks in Sanity

Adding codeblocks was a pretty painless experience, although the syntax highlighting was a little more complicated. In this article, I'll walk through the steps to add this to your Sanity+Next.js site.

This way of syntax highlighting is based on prismjs and this is a way to do server side syntax highlighting, which means no heavy js-libraries for the client to load!

This example is at work in this blog, and this whole blogs' code is available on GitHub by clicking here.

Installation

First up, you need the @sanity/code-input plugin.

Plugin

Sanity Schema

For the Sanity schema, this needs to be present, accompanied with the Sanity/code-input -plugin.

  • Optional: withFilename and highlightedLines

And finally, component looks like this in it's purest form, with some tailwindCSS you can remove yourself.

That was the simples way to add code blocks in your React website using Sanity CMS.

Next, let's look at adding syntax highlighting, and line highlighting.

Syntax highlighting

For syntax highlighting we are going to be using prism-react-rerenderer

Next, you have to import the package, and use the <Highlight /> component in your code. If you copied the prior codeBlock.jsx -file, you can replace the <pre> completely.

There you go! Now you can highlight the lines of code in your sanity studio (by clicking the line numbers), and you'll have nicely styled syntax highlighting on your site!

Best part is, this works with server side rendering!

Resources

Here's some further resources to maybe help, if this article won't work for you:

Code line highlight with prism-react-renderer by tiagofsanchez

Another way to add prism-react-rerenderer by Diego Frayo

Alternative libraries

There are different libraries which handle syntax highlighting:

  1. react-syntax-highlighter, which completely failed on me when I first gave it a try.
  2. Prismjs, which this is based on, but go look to see how it works.
  3. Highlightjs - a really popular way to do this. Probably can find React-specific helper-libraries for this too.
Thank you for reading, hope this was useful to you!

Older Posts

Cover Image for Creating a password generator

Creating a password generator

I ran into a big problem with passwords. Here’s how I solved it.

Cover Image for Showcase: Why your website should care about interaction cost

Showcase: Why your website should care about interaction cost

Your eCommerce website should accomplish a few things exceptionally well - So what does interaction cost have to do with it?