👀 Our most exciting product launch yet 🚀 Join us May 8th for Sanity Connect

Trouble accessing referenced item name in Sanity document preview

4 replies
Last updated: Oct 22, 2022
hello!
I have a document that takes in a reference type - I'd like to be able to show the name of the referenced item in the preview but I'm having some trouble - all I can access and display is the _ref (id of the referenced item)

I also tried using a
previewComponent but it doesn't seem to pull through, not sure why,
This is my current document
🙂
import PreviewComponent from "../../components/PreviewComponent";
import { FaStar as icon } from 'react-icons/fa';

export default {
  name: 'specialOffer',
  title: 'Special Offers',
  type: 'document',
  icon,
  fields: [
    {
      name: 'title',
      title: 'Offer Name',
      type: 'string',
      description: 'Title of the special offer',
    },
    {
      name: 'hotelId',
      title: 'Assigned Hotel',
      type: 'reference', 
      to: [{ type: 'hotel' }],
      options: {
        disableNew: true,
      },
    },
  ],
  preview: {
    select: {
      title: 'title',
      subtitle: 'hotelId._ref'
    },
    prepare(props) {
      const { title, subtitle } = props
      console.log('subtitle', subtitle)
      return {
        title: `${title}`,
        subtitle
      }
    }
  }
};

Oct 21, 2022, 6:53 PM
I just joined the slack to ask my own help question, so I'm not going to be useful in that regard. But I saw this line
console.log('subtitle', subtitle)
and wanted to just say, if you're not familiar, one of my favorite super basic QOL logging tricks is to use an object wrapper. It creates the exact same effect as what you do with that line, but without having to type the property name twice. ie, instead do
console.log({ subtitle })
.
Just one of those little things that I love and figured I'd share in case you're not familiar.
Oct 21, 2022, 7:43 PM
Am I understanding correctly that you’ve tried to do something like
subtitle: hotelId.title
and been unable to access the title? You should be able to access the data on the hotel object using whatever that field is named in the hotel schema.
Oct 21, 2022, 7:48 PM
An example of what Dan is saying:

preview: {
    select: {
      title: 'title',
      subtitle: 'hotelId.name' // would give you the "name" of the referenced hotel if name is a field on the hotel document type
    }
   ... 
}

// if it is an array of assigned hotels
preview: {
    select: {
      title: 'title',
      subtitle: 'hotelId[0].name' // for first item in array of referenced hotels
    },
...
}
Oct 22, 2022, 7:57 AM
Thanks everyone, it was late in the day and I missed the obvious solution! It's all working now! 🙂
Oct 22, 2022, 12:26 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?