Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to display images from (block content) rich text in portable text

how to display images from (block content) rich text in portable text using sanity as backend and next js as front end.

my portable text look like this

<PortableText
 value={blog.body}
/>

no variable or const are associated with it.

display all text and other fields expect images.

like image 902
Mohid Naeem Avatar asked Nov 29 '25 01:11

Mohid Naeem


1 Answers

You can pass an object of components to render your custom content types such as images.

First, create an object for your PortableText custom components, and return your image component for the image type.

const myPortableTextComponents = {
  types: {
    image: ({ value }) => {
      return (
        <SanityImage {...value} />
      );
    },
  },
};

Second: Create your ImageComponent. I'm using the next-sanity-image plugin here to use the image with NextJS Image component.

import {useNextSanityImage} from 'next-sanity-image'
import Image from 'next/image';

const sanityConfig = sanityClient({
  projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
  dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,
  useCdn: true
});

const SanityImage = ({ asset }) => {
  const imageProps = useNextSanityImage(sanityConfig, asset);

  if (!imageProps) return null;

  return (<Image 
    {...imageProps}
    layout='responsive'
    sizes='(max-width: 800px) 100vw, 800px'
  />);
}

Finally, pass the custom components object to your PortableText component via the components prop.

<PortableText
  value={body}
  components={myPortableTextComponents}
/>

You can learn more about rendering PortableText in React here and more about the next-sanity-image plugin here

like image 158
Eytyy Avatar answered Dec 01 '25 15:12

Eytyy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!