Repository navigation
Replies: 2 comments
|
The reason every option feels wrong is that you're asking one mechanism to do two unrelated jobs. Rendering and snippet generation are separate pipelines in Storybook, so the clean version splits the problem instead of picking a compromise. The relevant detail is in const storyJsx = context.originalStoryFn(context.args, context);The snippet is serialized from
So use the decorator for rendering and const meta: Meta<typeof SimpleComponent> = {
component: SimpleComponent,
decorators: [
(Story, { parameters }) => (
<>
{parameters.customCss && <style>{parameters.customCss}</style>}
<Story />
</>
),
],
parameters: {
docs: {
source: {
transform: (code: string, ctx: any) => {
const css = ctx.parameters?.customCss;
if (!css) return code;
const block = `<style>{\`\n${css}\n\`}</style>`;
// Guard against the transform running more than once (#35889)
if (code.includes(block)) return code;
return `${block}\n${code}`;
},
},
},
},
};
export const CustomCSS: Story = {
args: { className: 'custom-class' },
parameters: {
customCss: dedent`
.custom-class { width: 100px; height: 150px; }
`,
},
};This gives you all three of your requirements. The story renders with the CSS because the decorator applies it. Both code blocks show the CSS because That last point is why I'd avoid The One thing to check on your side: if you ever set |
Uh oh!
There was an error while loading. Please reload this page.
Summary
I've been trying to figure out a good way to include custom CSS in a Story and it's code block so that
I found a few ways to do it, though I don't love any of them. I'd be curious to know how other people approach this and which option you like best.
Check out https://stackblitz.com/edit/custom-css-in-story-code?file=src%2Fstories%2FSimpleComponent.stories.tsx for a reproduction of everything I tried.
During this process, I found what I think is a bug where the code transform function is applied twice on docs pages. That's filed at http://github.com/storybookjs/storybook/issues/35889.
Additional information
Option (1)
Option (2)
Option (3)
Option (4)
Option (5)
Create a reproduction
https://stackblitz.com/edit/custom-css-in-story-code?file=src%2Fstories%2FSimpleComponent.stories.tsx
All reactions