Render Portable Text with Astro.
Note
This package is a fork of astro-portabletext by Tom Theisel, maintained under the @portabletext organization. All credit for the original design and implementation goes to Tom. It remains distributed under the original ISC License. See Migrating from astro-portabletext.
- Installation
- Basic usage
- Sanity integration
- Customizing components
PortableTextcomponent properties- Utility functions
- Migrating from
astro-portabletext - License
npm install @portabletext/astroPrerequisites: Astro v4.6 or newer.
Import the PortableText component and pass it a Portable Text value. The library provides sensible defaults for rendering all standard Portable Text elements, which you can override.
---
import {PortableText} from '@portabletext/astro'
const portableText = [
{
_type: 'block',
style: 'normal',
markDefs: [],
children: [
{_type: 'span', marks: [], text: 'This is a '},
{_type: 'span', marks: ['strong'], text: 'bold'},
{_type: 'span', marks: [], text: ' text example!'},
],
},
]
---
<PortableText value={portableText} />This library's predecessor is officially recommended by Sanity for rendering Portable Text in Astro projects. Helpful resources:
Default components are provided for all standard features of the Portable Text spec, with logical HTML defaults. Provided components are merged with the defaults, so you only need to provide the things you want to override.
View the default structure and output
{
type: {
/* Custom types go here */
},
block: {
h1: /* <h1 {...attrs}><slot /></h1> */,
h2: /* <h2 {...attrs}><slot /></h2> */,
h3: /* <h3 {...attrs}><slot /></h3> */,
h4: /* <h4 {...attrs}><slot /></h4> */,
h5: /* <h5 {...attrs}><slot /></h5> */,
h6: /* <h6 {...attrs}><slot /></h6> */,
blockquote: /* <blockquote {...attrs}><slot /></blockquote> */,
normal: /* <p {...attrs}><slot /></p> */
},
list: {
bullet: /* <ul {...attrs}><slot /></ul> */,
number: /* <ol {...attrs}><slot /></ol> */,
menu: /* <menu {...attrs}><slot /></menu> */,
},
listItem: {
bullet: /* <li {...attrs}><slot /></li> */,
number: /* <li {...attrs}><slot /></li> */,
menu: /* <li {...attrs}><slot /></li> */,
},
mark: {
code: /* <code {...attrs}><slot /></code> */,
em: /* <em {...attrs}><slot /></em> */,
link: /* <a {...attrs} href="..."><slot /></a> */,
'strike-through': /* <del {...attrs}><slot /></del> */,
strong: /* <strong {...attrs}><slot /></strong> */,
underline: /* <span {...attrs} style="text-decoration: underline;"><slot /></span> */
},
text: /* Renders plain text */,
hardBreak: /* <br /> */,
}Custom components give you control over how each node is rendered. Map a component to a whole node type, or to a specific property (style, mark type, list item type, etc.) of that node type.
---
import {PortableText} from '@portabletext/astro'
import Code from '../components/Code.astro'
import Link from '../components/Link.astro'
const portableText = [
// ... your Portable Text content
]
const components = {
// Custom object types, keyed by `_type` (or a single component for all types)
type: {code: Code},
// Block styles, keyed by `style`
block: {/* h1, h2, normal, ... */},
// Lists, keyed by `listItem`
list: {/* bullet, number, ... */},
// List items, keyed by `listItem`
listItem: {/* bullet, number, ... */},
// Marks (decorators and annotations), keyed by mark type
mark: {link: Link},
// Fallbacks for unknown nodes
unknownType: undefined,
unknownBlock: undefined,
unknownList: undefined,
unknownListItem: undefined,
unknownMark: undefined,
// Plain text spans and hard breaks
text: undefined,
hardBreak: undefined,
}
---
<PortableText value={portableText} components={components} />Each custom component receives node, index and isInline props, and renders any children through a <slot />. For example, a custom link mark:
---
import type {MarkProps} from '@portabletext/astro/types'
export type Props = MarkProps<{href?: string}>
const {node} = Astro.props
const href = node.markDef?.href
---
<a href={href}><slot /></a>Slots provide a flexible way to enhance rendering by passing additional props to the resolved component - for example applying custom classes or wrapping elements - without replacing the default component entirely.
---
import {PortableText} from '@portabletext/astro'
const portableText = [
// ... your Portable Text content
]
---
<PortableText value={portableText}>
<fragment slot="mark">
{({Component, props, children}) => (
<Component {...props} class="mark">{children}</Component>
)}
</fragment>
</PortableText>
<style>
.mark:where(strong) {
/* some styles */
}
</style>A slot named after a node type applies to every node of that type: type, block, list, listItem, mark, text and hardBreak. To target a single block style, list type, mark type or custom type, scope the slot name with nodeType:type.
<PortableText value={portableText}>
<fragment slot="block:h1">
{({Component, props, children}) => (
<Component {...props} class="heading">{children}</Component>
)}
</fragment>
<fragment slot="mark:link">
{({Component, props, children}) => (
<Component {...props} rel="noopener">{children}</Component>
)}
</fragment>
<fragment slot="type:callout">
{({props}) => <aside class="callout">{props.node.text}</aside>}
</fragment>
</PortableText>A slot only has a Component to render when the node type has one. Standard block styles, list types and mark types all ship defaults, but components.type starts out empty - a custom type has no default component. So a slot for a custom type either renders its own markup, as type:callout does above, or registers a component to receive:
<PortableText value={portableText} components={{type: {callout: Callout}}}>
<fragment slot="type:callout">
{({Component, props}) => <Component {...props} class="callout" />}
</fragment>
</PortableText>Asking for Component when the node type has none gives you the unknown-type component and reports the missing component through onMissingComponent. A slot that never touches Component renders cleanly.
A scoped slot takes precedence over the node type it belongs to, so block can handle every block while block:h1 handles headings.
<PortableText value={portableText}>
<!-- Every block except `h1` -->
<fragment slot="block">
{({Component, props, children}) => (
<Component {...props} class="block">{children}</Component>
)}
</fragment>
<fragment slot="block:h1">
{({Component, props, children}) => (
<Component {...props} class="heading">{children}</Component>
)}
</fragment>
</PortableText>The text and hardBreak node types have no types of their own, so they cannot be scoped.
A slot does not replace the components prop, it wraps it. The Component handed to a slot is whatever the components prop resolved to for that node, so the two compose - the slot decides how the resolved component is rendered.
<PortableText value={portableText} components={{block: {h1: MyHeading}}}>
<fragment slot="block:h1">
<!-- `Component` is `MyHeading` -->
{({Component, props, children}) => (
<Component {...props} class="heading">{children}</Component>
)}
</fragment>
</PortableText>Slots belong to the author of the PortableText element, so they always win. A component reached through the components prop can customize its own children with render, but a slot for that node type takes precedence over it.
<PortableText value={portableText} components={{block: MyBlock}}>
<!-- Applies even if `MyBlock` renders its children with `render({mark: ...})` -->
<fragment slot="mark">
{({Component, props, children}) => (
<Component {...props} class="mark">{children}</Component>
)}
</fragment>
</PortableText>| Property | Type | Description |
|---|---|---|
value |
array or object |
Portable Text payload |
components (optional) |
object |
Mapping of components to node types or their properties. |
onMissingComponent (optional) |
function or boolean |
Disable warning messages or handle unknown types. Default prints to console. |
listNestingMode (optional) |
"html" or "direct" |
List nesting mode. Default is html. See ToolkitListNestMode. |
import {usePortableText, mergeComponents, toPlainText, spanToPlainText} from '@portabletext/astro'Within a component passed into the components prop, usePortableText(node) returns rendering utilities scoped to that node: getDefaultComponent(), getUnknownComponent() and render().
---
import type {BlockProps} from '@portabletext/astro/types'
import {usePortableText} from '@portabletext/astro'
export type Props = BlockProps
const {node} = Astro.props
const {getDefaultComponent} = usePortableText(node)
const Default = getDefaultComponent()
---
<Default {...Astro.props}><slot /></Default>Merges two component maps, giving priority to the overrides. Useful for extending a shared base set of components.
import {mergeComponents} from '@portabletext/astro'
const components = mergeComponents(baseComponents, {
block: {h1: MyHeading},
})Renders one or more Portable Text blocks as a plain string - handy for meta descriptions or generating slugs. spanToPlainText does the same for a single span's children.
---
import {toPlainText} from '@portabletext/astro'
const {node} = Astro.props
const text = toPlainText(node)
---@portabletext/astro is a drop-in fork of astro-portabletext. To migrate, swap the dependency and update your imports:
- import {PortableText} from 'astro-portabletext'
+ import {PortableText} from '@portabletext/astro'
- import type {BlockProps} from 'astro-portabletext/types'
+ import type {BlockProps} from '@portabletext/astro/types'The component API, props and utility functions are unchanged.
ISC © Tom Theisel (original author) and the Portable Text authors.