How to preview content on an object with an array of media in Sanity.io
9 replies
Last updated: Jul 30, 2022
AI Update
You can show different icons for images vs videos in your preview by using the prepare function to conditionally return an icon based on the media type. Here's how to approach it:
import { ImageIcon, PlayIcon } from "@sanity/icons";
export const mediaObjectType = defineType({
name: 'mediaObject',
type: 'object',
fields: [
{
name: 'mediaItems',
type: 'array',
of: [
{ type: 'image' },
{ type: 'file' } // for videos
]
}
],
preview: {
select: {
// Get the first media item from the array
firstMedia: 'mediaItems.0',
// You can also select the asset type directly if structured differently
mediaType: 'mediaItems.0._type'
},
prepare({ firstMedia, mediaType }) {
// Determine if it's a video or image
const isVideo = firstMedia?.asset?.mimeType?.startsWith('video/');
return {
title: 'Media Object',
subtitle: isVideo ? 'Video content' : 'Image content',
media: isVideo ? PlayIcon : (firstMedia ?? ImageIcon)
};
}
}
});For individual array items, you can configure previews on each media type:
{
name: 'mediaItems',
type: 'array',
of: [
{
type: 'image',
preview: {
select: {
media: 'asset'
},
prepare({ media }) {
return {
title: 'Image',
media: media ?? ImageIcon
};
}
}
},
{
type: 'file',
preview: {
select: {
fileName: 'asset.originalFilename',
mimeType: 'asset.mimeType'
},
prepare({ fileName, mimeType }) {
const isVideo = mimeType?.startsWith('video/');
return {
title: fileName || 'File',
subtitle: isVideo ? 'Video' : 'File',
media: isVideo ? PlayIcon : DocumentIcon
};
}
}
}
]
}The key points from Sanity's preview configuration:
- Use numeric indices to access array items in
select(e.g.,mediaItems.0for the first item) - The
preparefunction lets you conditionally return different icons based on the content - Always provide a fallback icon using the
??operator when media might not be available - You can check the
mimeTypeproperty on assets to distinguish between images and videos
This approach works for both the parent object preview and individual array item previews, giving you flexibility depending on where you need the icons to appear in Studio.
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.