Nesting PortableText components via components property in Sanity

7 replies
Last updated: Feb 7, 2023
have a
@portabletext/react
question — is it possible to nest
<PortableText />
JSX elements via the
components
property? My schema structure is as follows: I have an
array
of
block
and
imageWithCaption
fields, the
imageWithCaption
field is an
image
with subfield of
caption
which is also a
PortableText
block field.
I’ve attempted this already and nothing shows up where
<PortableText />
is supposed to be rendered so this seems like a no — but I’m curious is anyone has a similar use case and attempted other implementations of this.

// bodyText.ts
import linkObject from 'schemas/objects/link';
export default defineType({
  name: 'bodyText',
  title: 'Body Text',
  type: 'array',
  description: 'Enter the body text of this field note.',
  of: [
    {
      type: 'imageWithCaption',
    },
    {
      type: 'block',
     ...
    },
  ],
});

// imageWithCaption.ts
export default defineType({
  name: 'imageWithCaption',
  title: 'Image',
  type: 'image',
  options: {
    storeOriginalFilename: true,
  },
  fields: [
    {
      name: 'caption',
      title: 'Caption',
      type: 'caption',
      description: 'Enter the caption for this image.',
    },
    ...
  ],
});

// caption.ts
export default defineType({
  name: 'caption',
  title: 'Caption',
  type: 'array',
  of: [
    {
      type: 'block',
      styles: [{ title: 'Normal', value: 'normal' }],
      marks: {
        decorators: [
          { title: 'Strong', value: 'strong' },
          { title: 'Emphasis', value: 'em' },
          { title: 'Underline', value: 'underline' },
        ],
      },
      lists: [],
    },
  ],
});
AI Update

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:

  1. 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
        }
      }
    }
  2. Check that value.caption exists and is an array: The caption field should be an array of block objects, just like your main bodyText.

  3. Components can be reused or customized: You can pass the same components object 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.caption is 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 thread
7 replies
Yes, you can nest portable text renderers. It’s actually a pretty common case, especially for your use case for instance.
I have something like this in one of my projects (trimmed down to the bone for simplicity):

const document = {
  type: 'document',
  fields: [
    {
      type: 'array',
      of: [
        // Generic portable text stuff
        { type: 'block' },
        // The custom type
        { type: 'object', fields: [
          // … which has portable text has one of its field
          { type: 'array', of: [ { type: 'block' } ] }
        ] }
      ]
    }
  ]
}
hi kitty! that’s great news
it’s possible to render this with
@portabletext/react
?
Yeah, same thing on the frontend, you can have nesed renderers. 🙂
Something like this:
<PortableText
  value={props.value}
  components={{
    types: {
      imageWithCaption: (props) => (
        <figure>
          <img src={props.value.src} alt='' />
          <figcaption>
            <PortableText value={props.value.caption} />
          </figcaption>
        </figure>
      )
    }
  }}
/>
perfect i’ll give that a try

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.

Was this answer helpful?