Custom object preview in Portable Text block not working
Looking at your code, I can spot the issue! In your preview.select, you're using paths like metric.label, metric.keyNumber, etc., but since this schema IS the metric object itself, those fields are at the root level, not nested under metric.
Here's the corrected version:
preview: {
select: {
label: 'label', // Not 'metric.label'
keyNumber: 'keyNumber', // Not 'metric.keyNumber'
metricType: 'metricType' // Not 'metric.metricType'
},
prepare(data) {
let subtitlePrepend = ''
switch (data.metricType) {
case 'increase':
subtitlePrepend = 'Increase in'
break
case 'decrease':
subtitlePrepend = 'Decrease in'
break
default:
subtitlePrepend = ''
break
}
return {
title: data.keyNumber,
subtitle: subtitlePrepend ? `${subtitlePrepend} ${data.label}` : data.label
}
}
}A couple of other things I noticed:
The
metric.prefix: You'd only use dot notation likemetric.labelif you were accessing a referenced document or nested object. Since these fields are directly on this object, reference them directly.The
data.label.join(' '): Yourlabelfield is a string, not an array, so calling.join()on it would cause an error. I changed it to just usedata.labeldirectly.The subtitle logic: I simplified it to use a template literal for cleaner string concatenation.
Your switch logic and prepare function approach are totally fine! You don't need to move to a custom previewComponent for this - the standard prepare function is perfect for transforming data before display. Custom preview components are mainly useful when you need more complex rendering beyond title/subtitle/media.
Show original thread11 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.