Rich Text Blog Post - Unknown Block Type "Image"

1 replies
Last updated: Apr 10, 2022
Hi folks again!When i add image into my rich text blog post, it says

Unknown block type "image", specify a component for it in the `components.types` prop
does anyone know how to render images that are within the rich text block?
AI Update

When you add an image to your rich text blog post and see the error Unknown block type "image", specify a component for it in the components.types prop, it means you need to tell the Portable Text renderer how to display images.

Here's how to fix it:

Solution for @portabletext/react

If you're using the modern @portabletext/react library, add an image component to your components configuration:

import {PortableText} from '@portabletext/react'
import imageUrlBuilder from '@sanity/image-url'
import {createClient} from '@sanity/client'

const client = createClient({
  projectId: 'your-project-id',
  dataset: 'your-dataset',
  apiVersion: '2023-05-03',
  useCdn: true
})

const builder = imageUrlBuilder(client)

function urlFor(source) {
  return builder.image(source)
}

const components = {
  types: {
    image: ({value}) => {
      if (!value?.asset?._ref) {
        return null
      }
      return (
        <img
          alt={value.alt || ' '}
          loading="lazy"
          src={urlFor(value).width(800).url()}
        />
      )
    }
  }
}

// Then use it:
<PortableText value={yourContent} components={components} />

Key Points

  1. Install the image URL builder if you haven't already:

    npm install @sanity/image-url
  2. The components.types prop is where you define custom renderers for different block types in your Portable Text

  3. Access image data through value.asset._ref - this is the reference to the image in Sanity

  4. Use imageUrlBuilder to generate optimized image URLs with transformations like width, height, and format

You can customize this further by adding responsive images, different sizes, or styling. The Presenting Portable Text guide has more examples of customizing how different content types render.

Show original thread
1 reply

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?