Using a custom image as an icon in a Sanity project by overriding the media portion of a list preview.

3 replies
Last updated: Oct 13, 2023
Hello everyone, I want to use a custom image as Icon in my Sanity project. Does somebody know how I could apply an image instead of an Icon?
AI Update

You can use a custom image as an icon in Sanity Studio by returning a React component (including an <img> tag) from the prepare function in your schema's preview configuration. The media property accepts React components, not just image field references.

Here's how to use a custom image as an icon:

Using an Image from Your Project

If you want to use an image file from your project (like from a public or static folder):

export default {
  name: 'myDocument',
  type: 'document',
  fields: [...],
  preview: {
    select: {
      title: 'title',
    },
    prepare({ title }) {
      return {
        title: title,
        media: <img src="/path/to/your/image.png" alt="Custom icon" style={{width: '100%', height: '100%', objectFit: 'cover'}} />
      }
    }
  }
}

Using an Image from an External URL

preview: {
  select: {
    title: 'title',
  },
  prepare({ title }) {
    return {
      title: title,
      media: <img src="https://example.com/icon.png" alt="Custom icon" />
    }
  }
}

Using an Image Field from the Document

If you want to use an image that's stored in the document itself, you can reference it directly in the select object without needing a custom component:

preview: {
  select: {
    title: 'title',
    media: 'customIcon' // Reference to an image field in your schema
  }
}

Important Notes

  • The media property in the prepare function accepts any React component, so you can render custom JSX including <img> tags, SVGs, or even styled components
  • When using local images, make sure they're in your public folder (or equivalent static folder depending on your setup) so they're accessible at runtime
  • The preview system will handle the rendering and sizing automatically, but you may want to add inline styles to control how your image displays
  • For Studio v3, this approach works in list views within the document pane, but custom preview components may not display in the top-level Structure tool document list

You can find more details in the Sanity documentation on rendering React components in previews.

It would probably be best to override the
media
portion of a list preview .
thanks, that worked πŸ™‚
Great!

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?