Join live – Get insights, tips, + Q&A from Sanity developers on our latest releases

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

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
document were to have a field
of document type
, how can I write a preview for
such that it uses the preview of
to preview its
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
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
, 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
having a field
, I would like an instance of
to preview just as if I was previewing its field
. But do it in such a way that the preview definition of
knows treats the logic for the preview of
as a black box.
Without the latter constraint I could just duplicate the code, and prefix all select paths with
, 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
and with prefix
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
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?

Categorized in