astro-portabletext
Render Portable Text with Astro
Install
npm install astro-portabletext --save-dev
Usage
---
import { PortableText } from "astro-portabletext";
---
<PortableText
value={[/* portable text blocks */]}
components={/* custom components */}
/>
Default Components
astro-portabletext components will render the following
{
,
block: {
h1: ,
h2: ,
h3: ,
h4: ,
h5: ,
h6: ,
blockquote: ,
normal:
},
list: ,
listItem: ,
mark: {
code: ,
em: ,
link: ,
'strike-through': ,
strong: ,
underline:
},
hardBreak: ,
}
Merge/Override Components
Add to them or override a particular one
---
import { PortableText } from "astro-portabletext";
import { Unicorn } from "@component/Unicorn";
import { Dinosaur } from "@component/Dinosaur";
import { Sunny } from "@component/Sunny";
import { Highlight } from "@component/Highlight";
import { PageHeading } from "@component/PageHeading";
import { Bold } from "@component/Bold";
---
<PortableText
value={[/* portable text blocks */]}
components={{
type: {
unicorn: Unicorn,
dinosaur: Dinosaur,
},
block: {
h1: PageHeading, /* Override default `h1` block style */
sunny: Sunny, /* Custom block style */
},
mark: {
strong: Bold, /* Override default `strong` mark */
highlight: Highlight, /* Custom mark */
},
}}
/>
Custom Handler
Create a handler for better control
---
import { PortableText } from "astro-portabletext";
import { Type } from "@handler/Type"
import { Block } from "@handler/Block"
import { Mark } from "@handler/Mark"
---
<PortableText
value={[/* portable text blocks */]}
components={{
type: Type,
block: Block,
mark: Mark
}}
/>
Using <style>
in Astro component
---
import { PortableText } from "astro-portabletext";
import { Unicorn } from "@component/Unicorn";
---
<PortableText
value={[/* portable text blocks */]}
components={{
type: {
unicorn: Unicorn
}
}}
/>
<style>
.unicorn {}
</style>
export function Unicorn(props) {
const { astroClass = "" } = props;
return (
<div className={`unicorn ${astroClass}`}>
/* ... */
</div>
)
}
Typescript
import type { PtTypeComponentProps, TypedObject } from "astro-portabletext/types";
interface Greet extends TypedObject {
message: string
}
export function Greeting(props: PtTypeComponentProps<Greet>) {
return <p>Hello {props.node.message}</p>
}
Credits
@portabletext/react
@portabletext/svelte