If you're wondering how to use Astro components in Storybook, the short answer is you can't. Astro renders its components on the server side, making it impossible to load them into Storybook. Maybe the Astro Container API will make this easier in the future 🤞, but right now, it's not even close to the DX of Storybook.
That being said, if you're like me, you're probably only interested in the Astro Image component for all those groovy optimizations, so it makes sense to conjure up a sneaky workaround clever workflow.
The idea is to make a mock client-side image component that we pass in the Storybook context, then switch it out for the real thing later with Astro. Named slots will allow us to do this.
Here's a simple demo of a Figure component with an image and a caption in Preact.
// src/components/Figure.tsx
export default function Figure({ image, caption }) {
return (
<div class="flex flex-col">
{image}
<span>{caption}</span>
</div>
);
}
Because of serialization, args
don't work in Storybook with this approach, so do this instead:
// src/components/Figure.stories.tsx
import Figure from "./Figure";
import PreactImage as Image from "./PreactImage";
export default {
component: Figure,
};
const image = (
<PreactImage
src="https://cdn.shopify.com/static/sample-images/bath.jpeg"
width={800}
height={600}
alt="A lovely bath"
/>
);
export const Default = {
render: () => <Figure image={image} />,
};
Finally, swap it out with an Astro Image in the regular project. Notice the named image slot.
// pages/index.astro for example
---
import Figure from "../components/Figure";
import { Image } from "astro:assets";
---
<Figure >
<Image
slot="image"
src="https://cdn.shopify.com/static/sample-images/bath.jpeg"
width={800}
height={600}
alt="A lovely bath"
/>
</Figure>
Now you've got a Storybook that closely resembles the Astro build.
Top comments (0)