In Storybook how can you display the full source of a component in the "Show code" area of a story doc
Asked Answered
R

1

11

Right now in my team we are using Storybook v6 and the @storybook/addon-docs package in order to generate documentation for components.

In order to keep the .stories.mdx files small we write the story "showcase" components separately and then import them in the .stories.mdx files.

For example

// showcase/HugeComponentShowcase.jsx

import SomeComponent from 'components/SomeComponent';

export default function HugeComponentShowcase() {
  return <div>
    <p>This is a huge component showcase using SomeComponent</p>
    <SomeComponent propA propB propC/>
    <SomeComponent propB />
  </div>
}
// SomeComponent.stories.mdx

import { Meta, Story, Preview, Props } from '@storybook/addon-docs';
import HugeComponentShowcase from 'showcase/HugeComponentShowcase'; 

<Preview >
  <Story name="Generic component" >
    <HugeComponentShowcase />
  </Story>
</Preview>

This will result in this when you want to display the code of the showcase:

enter image description here

However what I want to be able to see there is:

<div>
  <p>This is a huge component showcase using SomeComponent</p>
  <SomeComponent propA propB propC/>
  <SomeComponent propB />
</div>

or at least the whole function body of HugeComponentShowcase.

I have tried adding this to the Story component

<Preview >
  <Story name="Generic component" parameters={{ docs: {source: { code: HugeComponentShowcase, } }}}>
    <HugeComponentShowcase />
  </Story>
</Preview>

But this ends up showing the compiled code of the component and not the original JSX code.

Redness answered 3/1, 2022 at 17:45 Comment(3)
Does this help? blog.krawaller.se/posts/…Comedietta
Hm, that's definitely one way to do it. It's not solving exactly the same issue but it gives an idea of how my issue can be tackled. I was hoping there was some baked-in way to achieve the desired result without having to write a webpack loader, but as I said, that's one way to do it, if there is no other option :)Redness
Storybook tends to focus on using the components, not the code of the components themselves.Comedietta
E
1

The only I've found to show the desired code on storybook, when using .mdx files it's by using the <Canvas mdxSource={'whatever you want to display'} ></Canvas>

Exhortation answered 9/3, 2023 at 15:3 Comment(1)
mdxSource is deprecated in later versions, so use <Canvas source={{ code: 'whatever you want to display' }} /> instead.Futurism

© 2022 - 2024 — McMap. All rights reserved.