Reputation: 71
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.
Upvotes: 3
Views: 5082
Reputation: 108
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
Upvotes: 6