Does anybody know how to show image caption in the BlockContent?

3 replies
Last updated: Nov 17, 2020

Hi!Does anybody know how to show image caption in the BlockContent?

I've added image caption field in the admin panel

{
     type: 'image',
     options: {hotspot: true},
     fields: [
       {
         name: 'caption',
         type: 'string',
         title: 'Caption',
         options: {
           isHighlighted: true
         }
       },
       {
         name: 'attribution',
         type: 'string',
         title: 'Attribution',
       }
    ]
}
And in the network I see

body {
 ...
 3: {
  assets: {...}
  caption: "here is the caption"
  _key: "..."
  _type: "image"
But how to display it on the page?
How to pass it into BlockContent on the from-end?

Nov 17, 2020, 1:19 PM

You need to use a serializer, more info here

Nov 17, 2020, 1:23 PM

Something like that

import React from "react"

const serializers = {
  types: {
    mainImage: ({ node }) => {
       if (!node || !node.asset || !node.asset._ref) {
     return null
  }
     return <img ... />
    }
  }
}

export default serializers

Nov 17, 2020, 1:27 PM

Thomas, thanks a lot! It's what I was looking for))

Nov 17, 2020, 2:50 PM

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.