How to display field value in Sanity schema preview section?
19 replies
Last updated: Dec 5, 2022
AI Update
Yes, absolutely! You need to use the select property to pass the field value to your prepare function. Here's how to fix your code:
fields: [
{
title: 'Title',
name: 'title',
type: 'string',
},
],
preview: {
select: {
title: 'title' // This selects the 'title' field
},
prepare({title}) { // The selected value is passed here as a parameter
return {
icon: MdTextFields,
title: title, // Now you can use it!
}
}
}The key is understanding how Sanity's preview configuration works:
select- Tells Sanity which fields to extract from your documentprepare- Receives those selected fields as parameters and returns what to display
You can also simplify this if you're just passing the title through without transformation:
preview: {
select: {
title: 'title'
}
// No prepare needed - Sanity will automatically use the title
}This pattern works for any field in your schema. You can select multiple fields too:
preview: {
select: {
title: 'title',
subtitle: 'description',
media: 'image'
},
prepare({title, subtitle, media}) {
return {
title: title,
subtitle: subtitle,
media: media ?? MdTextFields // Use icon as fallback
}
}
}The select object uses the field names from your schema, and those values become available in the prepare function parameters.
Show original thread19 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.