Nesting PortableText components via components property in Sanity
Yes, nesting <PortableText /> components via the components property is absolutely possible and is the correct approach for your use case! You're on the right track with your schema structure.
Here's how to handle nested Portable Text in your custom serializer:
import { PortableText } from '@portabletext/react';
const components = {
types: {
imageWithCaption: ({ value }) => (
<figure>
<img
src={value.asset.url}
alt={value.alt || ''}
/>
{value.caption && (
<figcaption>
{/* Nest PortableText here for the caption */}
<PortableText
value={value.caption}
components={components} // You can reuse the same components or pass a subset
/>
</figcaption>
)}
</figure>
)
}
};
// Then use it in your main component
<PortableText value={bodyText} components={components} />The key things to ensure:
Your GROQ query includes the caption data: Make sure you're fetching the nested caption array in your query:
*[_type == "yourType"][0] { bodyText[] { ..., _type == "imageWithCaption" => { ..., asset->, caption[] // Make sure this is included } } }Check that
value.captionexists and is an array: The caption field should be an array of block objects, just like your main bodyText.Components can be reused or customized: You can pass the same
componentsobject to nested PortableText instances, or create a simplified version if you want different rendering for captions.
If nothing is showing up, the most common issues are:
- The caption data isn't being fetched in your GROQ query
- The
value.captionis undefined or empty - There's a conditional that's preventing rendering
According to the @portabletext/react documentation, custom serializers receive the value prop (not node like in the old library) which contains all the data for that block, including nested fields.
Try adding some console logging to debug: console.log('imageWithCaption value:', value) to see what data you're actually receiving!
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.