Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

How to delegate a schema's preview to one of its fields in Sanity.io.

5 replies
Last updated: Aug 27, 2021
Hi all. Is there a way to "delegate" a schema's preview to one of its field? For instance, if a
Song
document were to have a field
artist
of document type
Artist
, how can I write a preview for
Song
such that it uses the preview of
Artist
to preview its
artist
field without copying over the code?
Aug 25, 2021, 2:10 PM
Hey User! Here’s a guide for configuring your preview to show fields from referenced documents .
Aug 25, 2021, 6:18 PM
Thanks
user M
! I had read through this already, but I don't want to show fields from referenced documents, I want to delgate the presentation that's defined in the referenced document. Whichever manner the referenced document's presentation is defined (with or without
media
, for instance), I want to have that same presentation without copying the code for the referenced document's presentation over and manually nesting the paths. Does this make sense?
Aug 26, 2021, 5:44 AM
I’m afraid I don’t understand, actually! Are you trying to have the referenced document define the preview on the document doing referencing, so that they effectively have the same preview?
Aug 26, 2021, 6:30 PM
That's it. So with type
A
having a field
b
referencing
B
, I would like an instance of
A
to preview just as if I was previewing its field
b
. But do it in such a way that the preview definition of
A
knows treats the logic for the preview of
B
as a black box.
Without the latter constraint I could just duplicate the code, and prefix all select paths with
b.
, but this create a rather tricky situation for code maintenance as my intention is now non-trivially duplicated.
Now that I say it out loud, I suppose I could define the preview logic as a reusable function:


const previewB = (prefix = "") => ({
  select: {
    title: `${prefix}someTitleField`,
    /* ... */
  },
  /* ... prepare ... */
})
And then evaluate this without arguments for
B
and with prefix
b.
for
A
.
Aug 27, 2021, 12:13 AM
Ah, got it! Thanks for bearing with me while I tried to understand! The one thing I think you're going to struggle with here is that the
preview
function cannot handle async and you would need that to get the details of the referenced document.
Aug 27, 2021, 3:22 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?