How to query array of images in Sanity schema?
name: 'carousel',
type: 'document',
title: 'Carousel',
fields:[
{ name:'imgContainer',
type:'array',
of:[
{ name: 'image',
type: 'image',
},
]
},
],
Welcome to the Sanity community! 🙂
For your carousel schema with an array of images, here's how to query it using GROQ:
Basic query to get all carousel documents:
*[_type == "carousel"]Get carousel with the image array:
*[_type == "carousel"]{
_id,
imgContainer
}Get carousel with expanded image URLs:
*[_type == "carousel"]{
_id,
imgContainer[]{
asset->{
_id,
url
}
}
}The key syntax here is imgContainer[] which iterates over each item in your array. The asset-> part dereferences the image asset reference to get the actual image data including the URL.
Get a specific carousel document:
*[_type == "carousel" && _id == "your-document-id"][0]{
imgContainer[]{
asset->{
url,
metadata {
dimensions
}
}
}
}In your frontend code (like React/Next.js), you'd use this query with the Sanity client:
import { client } from './sanityClient'
const query = `*[_type == "carousel"]{
imgContainer[]{
asset->{
url
}
}
}`
const carousels = await client.fetch(query)Then map over the results:
carousels[0].imgContainer.map((img) => (
<img src={img.asset.url} alt="" />
))The [] syntax in GROQ is a pipeline component that iterates over array elements, and the -> operator follows references to get the actual image data. This is the standard pattern for working with arrays of images in Sanity!
Show original thread3 replies
Was this answer helpful?
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.