Unlock seamless workflows and faster delivery with our latest releases – get the details

How to show the filename instead of position in an image block in Sanity.io

2 replies
Last updated: Jun 7, 2023
Hello. I have an image block that includes some fields, added to portable text:
export default {
  name: 'blockContent',
  title: 'Content',
  type: 'array',
  of: [
    {
      type: 'block',
    },
    {
      type: 'image',
      fields: [
        {
          name: 'position',
          title: 'Position',
          type: 'string',
          options: {
            list: [
              {title: 'Default', value: 'default'},
              {title: 'Left', value: 'left'},
              {title: 'Right', value: 'right'},
            ],
          },
        },
        {
          name: 'alt',
          title: 'Alternative text',
          type: 'localeString'
        },
      ],
    },
  ]
}
With this setup, the title in the image preview is showing the
position
string instead of the filename. How can I show the filename instead?Also, is there any way of having one of the
position
list items as the pre-selected default?
Jun 7, 2023, 4:48 PM
Hi
user E
. To show the filename, you can use a preview (as a sibling to the
fields
array in your schema) that specifies a
title
of
asset.originalFilename
. To set a
position
as a default (in this case, using the value in your list of
'default'
, but this could be anything), you can use the
initialValue
prop on the schema . Both are reflected below:

{
  type: 'image',
  fields: [
    {
      name: 'position',
      title: 'Position',
      type: 'string',
      options: {
        list: [
          {title: 'Default', value: 'default'},
          {title: 'Left', value: 'left'},
          {title: 'Right', value: 'right'},
        ],
      },
      initialValue: 'default',
    },
    {
      name: 'alt',
      title: 'Alternative text',
      type: 'localeString'
    },
  ],
  preview: {
    select: {
      title: 'asset.originalFilename',
    },
  },
},
Jun 7, 2023, 5:05 PM
By using the title for the preview the image disappeared, but I added it back with
media: 'asset'
. Thanks for your help!
Jun 7, 2023, 7:01 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?