Portable Text "Unknown block type 'code'" despite adding serializer
I see the issue! Your CodeRenderer component is calling BlockContent.defaultSerializers.types.block(props), which is actually rendering it as a regular text block instead of a code block. This is why you're still getting the error.
Here's what you need to fix:
import BlockContent from '@sanity/block-content-to-react'
const CodeRenderer = props => {
console.log('Render code block: ', props)
return (
<pre>
<code>{props.node.code}</code>
</pre>
)
}
<BlockContent
blocks={post._rawExcerpt}
serializers={{
types: {
code: CodeRenderer
}
}}
/>The key points:
- Access the code content via
props.node.code(not by calling the default block serializer) - Return actual code markup - typically a
<pre><code>combination - If your schema includes a language field, you can access it via
props.node.languagefor syntax highlighting
If you want to add syntax highlighting, you could use something like:
import SyntaxHighlighter from 'react-syntax-highlighter'
const CodeRenderer = props => {
return (
<SyntaxHighlighter language={props.node.language || 'text'}>
{props.node.code}
</SyntaxHighlighter>
)
}Important note: The @sanity/block-content-to-react package is deprecated. For new projects, you should use @portabletext/react instead. The migration is straightforward - the main difference is using a components prop instead of serializers, and accessing value instead of node:
import {PortableText} from '@portabletext/react'
const components = {
types: {
code: ({value}) => (
<pre>
<code>{value.code}</code>
</pre>
)
}
}
<PortableText value={post._rawExcerpt} components={components} />Show original thread9 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.