Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

Error displaying images in blockcontent, resolved with custom component type

3 replies
Last updated: Jun 23, 2023
Hi newbie here, I’m trying to display images from blockcontent and I got this error:
PortableText [components.type] is missing “image”

And then I follow this page to try to define custom component type:


https://www.sanity.io/guides/ultimate-guide-for-customising-portable-text-from-schema-to-react-component
I’ve added this, but all I got is rendering error
😞 Would appreciate it if someone can point me in the right direction.

const Body = (props)=> {
  // we pass the content, width & height of the images into each instance of the Body component 
  // content is our array of blocks
  const { content, imgWidth, imgHeight } = props;
  
  const customBlockComponents = {
  // first we tackle our custom block types
  types: {
    image: ({value}) => {
      // we need to get the image source url, and since @sanity/image-url will give us optimised images for each instance we use it
      const imgUrl = urlForImage(value.assset).height(imgHeight).width(imgWidth).url()
      
      return <Image
            width={imgWidth}
            height={imgHeight}
            alt={value.alt}
            src={imgUrl}
            sizes="100vw"
            priority={false}
          />
    },
  },

  // then we define how the annotations should be rendered
  marks: {
    link: ({children, value}) => {
      const rel = !value.href.startsWith('/') ? 'noreferrer noopener' : undefined
      return (
        <a href={value.href} target='_blank' rel={rel}>
          {children}
        </a>
      )
    },
    internalLink: ({children, value}) => {
      return (
        <a href={value.href}>
          {children}
        </a>
      )
    },
  },
}

return <PortableText
  value={content}
  components={customBlockComponents}
/>
}
Jun 18, 2023, 12:47 PM
It looks like
asset
is spelled
assset
in your image handler. That may be causing it to error out.
Jun 22, 2023, 3:51 PM
Ah, I didn’t see that. But I solved it in the end, by changing the codes completely. It worked…:P Thanks for the help anyway!
Jun 23, 2023, 6:11 AM
Glad you got it working 🙂
Jun 23, 2023, 4:24 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?