Best practice for specifying alt text for images in block text using Sanity
The best practice for adding alt text to images embedded in block content is to extend your image block definition with a custom alt field. Here's how to set it up:
In your schema definition:
{
name: 'blockContent',
type: 'array',
of: [
{
type: 'block'
},
{
type: 'image',
options: {hotspot: true},
fields: [
{
name: 'alt',
type: 'string',
title: 'Alternative text',
description: 'Important for SEO and accessibility.',
validation: Rule => Rule.required()
}
]
}
]
}This adds an alt text field that appears directly below the image upload in Sanity Studio, making it easy for editors to add descriptive text for each image.
When rendering (using the current recommended approach):
Note that @sanity/block-content-to-react was deprecated in 2022. You should now use @portabletext/react instead. Here's how to render your images with alt text using the modern approach:
import {PortableText} from '@portabletext/react'
import imageUrlBuilder from '@sanity/image-url'
const builder = imageUrlBuilder(client)
const components = {
types: {
image: ({value}) => (
<img
src={builder.image(value).url()}
alt={value.alt || 'Image'}
/>
)
}
}
<PortableText
value={content}
components={components}
/>The key differences from the old library:
- Use
componentsprop instead ofserializers - Use
valueprop instead ofblocks - Access the image data through
valueinstead ofnodein your component
This approach gives you full control over how images are rendered and ensures the alt text stored in your content is properly used in your HTML output. You can learn more about custom blocks in Portable Text in the official documentation.
Show original thread8 replies
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.