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
{
type: {
},
block: {
h1: ,
h2: ,
h3: ,
h4: ,
h5: ,
h6: ,
blockquote: ,
normal:
},
list: {
bullet: ,
number: ,
},
listItem: {
bullet: ,
number: ,
},
mark: {
code: ,
em: ,
link: ,
'strike-through': ,
strong: ,
underline:
},
hardBreak: ,
}
Merge/Override Components
---
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
---
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.astro";
---
<PortableText
value={[/* portable text blocks */]}
components={{
type: {
unicorn: Unicorn
}
}}
/>
<style>
.unicorn {}
</style>
---
const { astroClass = "" } = Astro.props;
---
<div class={`unicorn ${astroClass}`}>
</div>
Typescript
components.type
---
import type { TypedObject, Props } from "astro-portabletext";
interface Greet extends TypedObject {
message: string;
}
type Greet = { message: string };
const { node } = Astro.props as Props<Greet>;
---
<h1>{node.message}</h1>
components.mark
---
import type { Mark, Props } from "astro-portabletext";
type Greet = Mark<{ message: string }>;
const { node } = Astro.props as Props<Greet>;
---
<p>{node.markDef.message}</p>
Alternatives
@portabletext/react
@portabletext/svelte