Publised 2022-07-03
Adding code blocks to Next.js & Sanity Blog
All you've done is wrap some text in a code element, and you're calling yourself a developer?
Look at this:
1let fancy = "code block"
I'm sure you're thinking wow, this is his first blog post? All you've done is wrap some text in a code element, and you're calling yourself a developer? Look, I completely get it, but hear me out. There's more to this than meets the eye.
I've built this blog using Next.js + ChakraUi, and Sanity.io as my CMS. You're probably wondering, why not just go with a Markdown-based blog? Then you could just throw your code in a code tag and call it a day. And you're right, I kind of wish I did. I thought it'd be cool to make the posts "open source", so people can contribute or update/fix the code blocks I'll likely screw up. But I was already in too deep with Sanity and didn't want to back out by that point, so I stuck to my guns.
Anyway, I digress. Sanity has a great WYSIWYG editor for content. Out of the box that comes with default headings, bullet points and image insertion. But, most importantly, it's missing the ability to add code blocks. To add a bit more complexity to the mix, it also uses @portablerichtext/react
to render elements. By default, it doesn't render code
blocks. Being a development blog, I wanted the ability to insert and display nice-looking code blocks. Below, I've gone over two separate ways to implement these features.
Easy Way
The easy way is great if you want to render out some nice, styled inline-code
. This is great for referencing, say, npm packages inline, file paths or simple, one-liner commands.
If you used the default blog template when running sanity init
, you should already have the files used in the instructions.
Navigate to /schemas/blogContent.js
and find the decorators array, as show below.
1marks: {
2 decorators: [
3 ...
4 ]
5}