Setting the file. One moment.
Skill 04 · Portable Text Serialization
Subchapter 4.1
rules/astro.mdMarkdown2 KBView on GitHub
Use astro-portabletext to render PT in Astro projects. This is the officially recommended library for Sanity + Astro.
---
import {PortableText} from 'astro-portabletext'
const {value} = Astro.props
---
<PortableText value={value} />Pass custom components to override default rendering:
---
import {PortableText} from 'astro-portabletext'
import ImageBlock from './ImageBlock.astro'
import CodeBlock from './CodeBlock.astro'
import Link from './Link.astro'
const {value} = Astro.props
const components = {
type: {
image: ImageBlock,
code: CodeBlock,
},
mark: {
link: Link,
},
block: {
h1: 'h1',
h2: 'h2',
blockquote: 'blockquote',
},
}
---
<PortableText {value} {components} />---
// ImageBlock.astro
const {node} = Astro.props
---
<figure>
<img src={urlFor(node).width(800).url()} alt={node.alt || ''} />
{node.caption && <figcaption>{node.caption}</figcaption>}
</figure>---
// Link.astro
const {node} = Astro.props
const href = node?.href || ''
const rel = href.startsWith('/') ? undefined : 'noreferrer noopener'
---
<a {href} {rel}><slot /></a>astro-portabletext supports Astro’s slot system for simpler customization:
---
import {PortableText} from 'astro-portabletext'
---
<PortableText value={value}>
<fragment slot="block:h1">
<h1 class="text-4xl font-bold"><slot /></h1>
</fragment>
<fragment slot="mark:strong">
<strong class="font-black"><slot /></strong>
</fragment>
</PortableText>For more control, use the usePortableText render function:
---
import {usePortableText} from 'astro-portabletext'
const {value} = Astro.props
const {render} = usePortableText(value)
---
<div class="prose">
{render()}
</div>