🔮 Sanity Create is here. Writing is reinvented. Try now, no developer setup

Creating custom block previews for images with fields in Slack thread.

6 replies
Last updated: Jun 16, 2021
Is it possible to create custom block previews for images with fields? I'd like to do something like this:

export const richImage = {
  name: 'richImage',
  type: 'image',
  title: 'Image',
  options: {
    hotspot: true,
  },
  fields: [
    {
      name: 'caption',
      title: 'Caption',
      type: 'string',
      options: {
        isHighlighted: true,
      },
    },

    {
      name: 'altText',
      title: 'Alt Text',
      type: 'string',
      description:
        'A short description of the image. Helps with accessibility and SEO',
      options: {
        isHighlighted: true,
      },
    },
  ],
  preview: {
    select: {
      caption: 'caption',
      altText: 'altText',
    },
    prepare: ({ caption, altText }) => {
      return {
        title: caption,
        subtitle: `alt: ${altText}`,
      };
    },
  },
};
This works, but the thumbnail image is no longer in the preview (see the thread
👉)
Jun 16, 2021, 1:35 AM
Without any preview config specified:
Jun 16, 2021, 1:38 AM
Hey User, you’re not selecting or preparing the image 🤔
Jun 16, 2021, 1:43 AM
Here’s a similar schema we use:
Jun 16, 2021, 1:43 AM
const imageWithMeta = {
  title: 'Image',
  name: 'imageWithMeta',
  type: 'image',
  options: {
    metadata: ['palette', 'lqip'],
    hotspot: true
  },
  fields: [
    {
      name: 'alt',
      type: 'string',
      title: 'Alt',
      options: {
        isHighlighted: true
      }
    },
    {
      name: 'caption',
      type: 'string',
      title: 'Caption',
      options: {
        isHighlighted: true
      }
    }
  ],
  preview: {
    select: {
      title: 'alt',
      subtitle: 'caption',
      media: 'asset'
    }
  }
}
Jun 16, 2021, 1:43 AM
You should just be able to extend your preview block to…

preview: {
    select: {
      caption: 'caption',
      altText: 'altText',
      media: 'asset'
    },
    prepare: ({ caption, altText, media }) => {
      return {
        title: caption,
        subtitle: `alt: ${altText}`,
        media
      };
    },
  },
Jun 16, 2021, 1:47 AM
Got it, I didn't realize I could select the asset! Thank you 🙂
Jun 16, 2021, 2:24 AM

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?