How to preview the first element in an array of references?

2 replies
Last updated: Nov 1, 2020
Hi everyone! I know that I can preview references like this:
preview: {
  select: {
    title: 'title',
    subtitle: 'referenceField.referencedTitle'
 }
}
But now I have an array of references and I would like to preview the first element in the array. This doesn't work for me:


preview: {
  select: {
    title: 'title',
    subtitle: 'referenceArrayField[0].referencedTitle'
 }
}
Is this technically possible? Thanks for any pointers
😃
AI Update

Good news - yes, this is technically possible! You can access array elements in preview select using dot notation with numeric indices.

The syntax you need is slightly different from what you tried. Instead of bracket notation [0], use dot notation like this:

preview: {
  select: {
    title: 'title',
    subtitle: 'referenceArrayField.0.referencedTitle'
  }
}

This is documented in the official preview configuration docs, which specifically mentions this pattern:

We encourage you only to select a subset of the array values: authors.0.name ← authors.0 is a reference to author, and the .name dereferences into it

So for your case:

  • referenceArrayField.0 accesses the first element in your array of references
  • .referencedTitle then dereferences into that reference to grab the title field

Important note: The preview select can only access a limited subset of array values - it's designed for simple cases like showing the first author or first image. If you need more complex logic (like showing multiple array items or doing conditional logic), you'll want to use the prepare function:

preview: {
  select: {
    title: 'title',
    firstRef: 'referenceArrayField.0.referencedTitle',
    secondRef: 'referenceArrayField.1.referencedTitle'
  },
  prepare({title, firstRef, secondRef}) {
    return {
      title: title,
      subtitle: firstRef || secondRef || 'No references'
    }
  }
}

This gives you more flexibility to handle cases where the array might be empty or you want to format the display differently.

Show original thread
2 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.

Was this answer helpful?