How to render code blocks with SanityContent components?
I can help you with rendering code blocks in your Portable Text! The issue you're experiencing is common - code blocks from Sanity need custom components to render properly, otherwise they'll just appear as plain text.
When you use the @sanity/code-input plugin to add code blocks to your rich text in Sanity Studio, those blocks are stored in your Portable Text as custom block types. To render them properly on the frontend, you need to tell your Portable Text renderer how to handle the code type specifically.
For Astro with astro-portabletext
If you're using astro-portabletext, you need to pass custom components via the components prop. Here's how to render code blocks:
---
import { PortableText } from 'astro-portabletext';
import Code from './Code.astro'; // Your custom code component
const components = {
type: {
code: Code,
}
};
---
<PortableText value={yourPortableTextContent} components={components} />Then create a Code.astro component:
---
// Code.astro
const { language, code } = Astro.props.value;
---
<pre data-language={language}>
<code>{code}</code>
</pre>For React-based frameworks
If you're using React with @portabletext/react, the pattern is similar:
import { PortableText } from '@portabletext/react';
const components = {
types: {
code: (props) => {
const {language, code} = props.value;
return (
<pre data-language={language}>
<code>{code}</code>
</pre>
);
}
}
};
<PortableText value={content} components={components} />For Nuxt with @nuxtjs/sanity
In Nuxt, you'd use the serializers or components prop depending on your version:
<SanityContent :blocks="content" :serializers="serializers" />
const serializers = {
types: {
code: (props) => {
return h('pre', { 'data-language': props.language }, [
h('code', props.code)
]);
}
}
}Adding syntax highlighting
For proper syntax highlighting, you can integrate libraries like Prism.js or highlight.js:
---
// Enhanced Code.astro with syntax highlighting
import Prism from 'prismjs';
const { language, code } = Astro.props.value;
const highlighted = Prism.highlight(code, Prism.languages[language] || Prism.languages.javascript, language);
---
<pre class={`language-${language}`}>
<code set:html={highlighted} />
</pre>The key takeaway: Portable Text renderers need explicit instructions on how to handle custom block types like code blocks. Without defining these components/serializers, they'll fall back to default rendering which treats them as plain paragraphs.
Check out the official guide on presenting Portable Text for more details on customizing your Portable Text output!
Show original thread2 replies
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.