Sanity code-input plugin: Cannot read properties of undefined (reading 'code')
Looking at your error, the issue is that you're using data to access the code properties, but with Portable Text in Sanity v3, the correct property is value, not data.
The code-input plugin stores its content in a specific structure, and when you're rendering it through PortableText, you need to access it via value.code, value.filename, and value.language.
Here's the corrected version of your RichTextComponents:
export const RichTextComponents = {
types: {
code: ({ value }) => { // Changed from 'data' to 'value'
const code = value.code;
const filename = value.filename;
const language = value.language;
return (
<div>
<div className="flex justify-between ">
<p className="opacity-70">{filename}</p>
<p>
language: <span className="opacity-70">{language}</span>
</p>
</div>
<pre className="p-2">
<code>
{code}
</code>
</pre>
</div>
);
},
},
// ...rest of your components
};The key change is ({ data }) → ({ value }). This is the standard way custom types are passed to serializers in @portabletext/react, which is what the <PortableText> component uses under the hood.
If you want to add syntax highlighting (which you mentioned in your comment), you could integrate a library like Prism or react-syntax-highlighter:
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { vscDarkPlus } from 'react-syntax-highlighter/dist/cjs/styles/prism';
code: ({ value }) => {
return (
<div>
{value.filename && (
<div className="flex justify-between bg-gray-800 px-4 py-2 text-sm text-gray-300">
<p>{value.filename}</p>
<p>language: <span className="opacity-70">{value.language}</span></p>
</div>
)}
<SyntaxHighlighter language={value.language} style={vscDarkPlus}>
{value.code}
</SyntaxHighlighter>
</div>
);
}That should fix your error and get your code blocks rendering properly!
Show original thread7 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.