How to loop over Arrays of different Objects in Sanity?
Great question! The serializer pattern is indeed a really clean approach for handling arrays of different object types. It's the same pattern that makes Portable Text rendering so elegant, and it works beautifully for any array with mixed types.
Here's the basic pattern that mirrors how serializers work for Portable Text:
// Define your type handlers
const typeHandlers = {
youTube: (item) => <YouTubeEmbed {...item} />,
blogPost: (item) => <BlogPostCard {...item} />,
imageGallery: (item) => <Gallery images={item.images} />,
// ... more types
}
// Loop through your array
{items.map((item) => {
const Handler = typeHandlers[item._type]
return Handler ? (
<Handler key={item._key} {...item} />
) : null
})}Or if you prefer a more functional approach:
const renderItem = (item) => {
switch(item._type) {
case 'youTube':
return <YouTubeEmbed {...item} />
case 'blogPost':
return <BlogPostCard {...item} />
case 'imageGallery':
return <Gallery images={item.images} />
default:
return null
}
}
{items.map((item) => (
<Fragment key={item._key}>
{renderItem(item)}
</Fragment>
))}The key benefits of this pattern:
- Type safety: Each handler knows exactly what props to expect
- Maintainability: Adding new types is just adding a new handler
- Separation of concerns: Rendering logic is separate from the loop logic
- Reusability: Handlers can be shared across components
This works great with Sanity's array fields that support multiple member types, where you might have a schema like:
{
name: 'content',
type: 'array',
of: [
{type: 'youTube'},
{type: 'blogPost'},
{type: 'imageGallery'}
]
}The _type property on each array item tells you which handler to use, and the _key property (automatically added by Sanity) gives you a stable key for React's reconciliation.
Much cleaner than a bunch of nested conditionals!
Show original thread2 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.