✨Discover storytelling in the AI age with Pixar's Matthew Luhn at Sanity Connect, May 8th—register now

How to preview content on an object with an array of media in Sanity.io

9 replies
Last updated: Jul 30, 2022
Hey folks, how would I preview content on an object that has an array of media? Ideally I’d like to show an icon depending on whether is media is a video or an image.
Jul 22, 2022, 6:56 PM
The object within my document array:
Jul 22, 2022, 6:56 PM
The media array in the object
Jul 22, 2022, 6:56 PM
Hey
user A
! You can create a custom preview . In your
prepare
function, you'll want to conditionally render your icon. If you share your schema and the fields you're checking against I can be more specific.
Jul 22, 2022, 7:01 PM
Thanks
user M
, here’s the schema for the object:

export default {
  title: "Media Section",
  name: "mediaSection",
  type: "object",
  fields: [
    {
      title: "Media",
      name: "media",
      type: "array",
      of: [{ type: "img" }, { type: "video" }],
      validation: (Rule) => Rule.max(3),
    },
  ],
  preview: {
    select: {
      title: "media.0.alt",
      media: "media.0",
      mediaType: "media.0._type",
    },
    prepare({ title, media, mediaType }) {
      return {
        title: title,
        media: media,
        icon: mediaType == "image" ? FiImage : FiFilm,
      };
    },
  },
};
Jul 22, 2022, 7:04 PM
Hello
user A
another question (I am trying to replicate your question):Would you like the preview to be only the icon or would you like to have an additional icon next to a preview of the uploaded `img`/`video`?
There are different ways to do so, and the schema you shared is about both as far as I can see…

You can specify an icon in the `img`/`video` schemas, which will then be displayed in the options in
+ Add Item
(see pic) or add an icon in the preview of the array in the Media section.
Jul 26, 2022, 9:52 AM
Hi
user J
, I would like only one thing to show. Ideally, if it’s an image, we preview the image. And if it’s a video, then show the icon (I’m using vimeo so I don’t think we can preview the asset directly?)
Jul 28, 2022, 9:06 PM
The icons show up in the “Media section” array as intended, but I would like to show the preview in the the parent component aka the “Project contents” array as well so that it’s easy to know what’s in each “Media section”
Jul 28, 2022, 9:08 PM
ah! So can you add this schema as well? 🙂
Jul 29, 2022, 6:39 PM
Looks like I ended up figuring this out! Thanks for all the help 🙏
Jul 30, 2022, 12:12 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?