How to query array of images in Sanity schema?

3 replies
Last updated: Jan 17, 2023
Hi All, I am new here πŸ™‚ , I have got this schema, I need help with the query to access the data in the array
name: 'carousel',

type: 'document',

title: 'Carousel',


fields:[

{

name:'imgContainer',

type:'array',

of:[

{

name: 'image',

type: 'image',

},

]

},

],
AI Update

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 thread
3 replies
After you deploy, because deploying is far more easier than using your own PC's resources, just create a document of this Schematype and hit Crtl+Alt+I to show you the object properties you can use in groq queries to access the data inside your schematype., Let me know if that helps.
*[_type == "carousel"]{
"images": imgContainer[] -> {
"image": image.asset -> url
}}
This just game an idea for my own project, thank you

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?