Use object title in pageBuilder preview
Yes, you can definitely use the object's schema type title in the preview! The key is to manually set it in your prepare function. While the prepare function doesn't automatically receive access to schema metadata, you can simply reference the title you've already defined in your schema.
Here's how to do it for a pageBuilder array:
{
name: 'twoImages',
type: 'object',
title: 'Two Images',
fields: [
// your fields here
],
preview: {
prepare() {
return {
title: 'Two Images', // Use your schema title here
subtitle: 'Your custom subtitle here'
}
}
}
}For better maintainability, you can store the title in a constant so you don't repeat yourself:
const TWO_IMAGES_TITLE = 'Two Images';
export default {
name: 'twoImages',
type: 'object',
title: TWO_IMAGES_TITLE,
fields: [
// your fields here
],
preview: {
prepare() {
return {
title: TWO_IMAGES_TITLE,
subtitle: 'Your custom subtitle here'
}
}
}
}According to the preview configuration documentation, the prepare function receives the selection object containing the fields you've selected, but it doesn't have built-in access to schema metadata. The approach above ensures your preview displays the schema type title consistently.
You can also combine this with selected fields if you want to show both the type name and some dynamic content:
preview: {
select: {
image: 'images.0' // select first image if you have one
},
prepare(selection) {
return {
title: 'Two Images',
subtitle: selection.image ? 'Has images' : 'No images yet',
media: selection.image
}
}
}This pattern works great for pageBuilder arrays where you have multiple object types and want each to clearly display what type of block it is!
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.