How to loop over Arrays of different Objects in Sanity?

2 replies
Last updated: Mar 16, 2021
Speaking of structure and patterns – how do you all loop over your Arrays of different Objects? I had come up with a much messier version of this in the past. But then was thinking about it like how
serializers
works and think it’s much cleaner.
AI Update

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:

  1. Type safety: Each handler knows exactly what props to expect
  2. Maintainability: Adding new types is just adding a new handler
  3. Separation of concerns: Rendering logic is separate from the loop logic
  4. 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 thread
2 replies
I actually use this pattern a lot, so created a function to handle this! Its the renderObjectArray function in https://www.npmjs.com/package/sanity-react-extra
Neat!

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.

Was this answer helpful?