How do I render the image in Sanity blockcontent into a custom image component?

4 replies
Last updated: Nov 28, 2020

How is it that i render the image in the blockcontent into a custom image component? like in a blogpost where I want to display images in the body section that are uploaded in the body which has block content type… this link (https://github.com/sanity-io/block-content-to-react ) didn't help me, as specifying imageOptions in BlockContent displays images very plainly, i couldn't control the width based on screen sizes and image zoom feature that I could implement if I could use a custom image component

Nov 26, 2020, 2:23 AM

Specify an image serializer.

const serializer = {
  types: {
    image: props => <img ... />
  }
}

Nov 26, 2020, 6:05 PM

I tried that too. But the problem i faced was I couldn’t get to pass the image data in the image tag. For example the only image src that might be helpful is in props.data.asset but that too only has _ref property, which isn’t a link to the image from sanity’s CDN. Do you have any idea where I could get the asset.fluid / asset.fixed data (say if wanted to render it inside gatasby image tag)

Nov 27, 2020, 11:33 AM

Pass the

asset
, (and
hotspot
, and
crop
properties, if present) to SanityImage , like this:
<SanityImage {...props} width={600} alt="" />

Nov 27, 2020, 2:32 PM

thanks a lot. A quick mention, it was

{...props.node}
that made it work for me.

Nov 28, 2020, 3:46 AM

Sanity.io: Get the most out of your content

Sanity.io is a platform to build websites and applications. It comes with great APIs that let you treat content like data. Give your team exactly what they need to edit and publish their content with the customizable Sanity Studio. Get real-time collaboration out of the box. Sanity.io comes with a hosted datastore for JSON documents, query languages like GROQ and GraphQL, CDNs, on-demand asset transformations, presentation agnostic rich text, plugins, and much more.

Don't compromise on developer experience. Join thousands of developers and trusted companies and power your content with Sanity.io. Free to get started, pay-as-you-go on all plans.