How to display custom icons in array item previews from referenced documents?
I understand your issue! When you have an array of references to your category documents, the preview configuration from the category schema doesn't automatically apply to how those references appear in the array. You need to configure the preview on the array field itself, not just on the referenced document type.
Here's how to fix it. In the schema where you have the array of categories, you need to add a preview configuration to the array field definition:
{
name: 'categories',
type: 'array',
of: [
{
type: 'reference',
to: [{type: 'category'}],
preview: {
select: {
title: 'categoryName',
subtitle: 'descriptionShort',
media: 'icon'
}
}
}
]
}The key is adding the preview object to the reference definition inside the array's of property. This tells Sanity how to display each reference when it appears in the array.
If you want to access fields from the referenced category document (which is the typical case), you can use dot notation in the select:
{
name: 'categories',
type: 'array',
of: [
{
type: 'reference',
to: [{type: 'category'}],
preview: {
select: {
title: 'categoryName', // This accesses the referenced category's categoryName
subtitle: 'descriptionShort',
media: 'icon'
}
}
}
]
}If you need more control or want to provide fallback icons, you can use the prepare function with a React icon component:
import { TagIcon } from '@sanity/icons'
{
name: 'categories',
type: 'array',
of: [
{
type: 'reference',
to: [{type: 'category'}],
preview: {
select: {
title: 'categoryName',
subtitle: 'descriptionShort',
media: 'icon'
},
prepare({title, subtitle, media}) {
return {
title,
subtitle,
media: media ?? TagIcon // Fallback icon if none exists
}
}
}
}
]
}The reason this happens is that preview configurations are context-specific in Sanity. The preview you defined on the category document type controls how categories appear in the category document list, but when those same categories are referenced in an array elsewhere, you need to explicitly tell Sanity how to preview them in that context. This gives you flexibility to show different information in different contexts if needed.
For more details on preview configuration, check out the official documentation on previews and list views and this helpful guide on creating richer array item previews.
Show original thread12 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.