Big white letter A and small grey letter A on a white background.
Photo by Alexander Andrews on Unsplash

Add custom blocks to portable text - part 1

Today I'm tackling one of the things on my to do list - adding custom code blocks to the existing portable text components on this sanity/gatsby site.

To do this, I need to edit the portable text block. In sanity studio, you'll find the bodyPortableText.js file in studio>schemas>objects. I edited the portable text object to add a code type. By now, I'm more than comfortable editing schemas but I need a little help with linking up the frontend - the serializers.

The video below sums up how to add code blocks, so watch this if you want to see how everything links up.

I'm using the sanity code input plugin which makes things much easier and has a lot of lovely inbuilt functionality.

So in serializers.js, we need to add the code type like this:

code: ({node = {}}) => {
  const { code, language } = node
  if (!code) {
    return null
  }
  return <SyntaxHighlighter language={language || "text"}>{code}</SyntaxHighlighter>
}

Did you see that? So that works then! I used this react syntax highlighter too, as outlined in the video above. Now to go back and update my other posts with this lovely new feature.

Part 2 will be adding video embed functionality...

Edit 30/12/2020

I noticed that there was an issue with line wrapping on the code blocks. Because the default is no-wrap, the text container was growing too wide and/or a horizontal scroll bar was being generated on the code blocks.

To fix this, I just edited the serializers.js file again to add the word breaks, white space and line wrap:

code: ({node = {}}) => {
  const { code, language } = node
  if (!code) {
    return null
  }
  return <SyntaxHighlighter 
          language={language || "text"} 
          style={colorBrewer} 
          lineProps={{style: {wordBreak: 'break-all', whiteSpace: 'pre-wrap'}}}
          wrapLines={true}>
            {code}
          </SyntaxHighlighter>
},

A little digital blog, by a little analog person

© 2021 Ashley Chin