Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storybook for React to show plain HTML source code with <Preview> Addon

I am using Preview addon in Storybook for React to show the component usage in Docs.

<Preview withToolbar>
  <Story name="primary">
  <PrimaryButton  disabled={boolean("Disabled",false)} modifiers={["small"]} onClick={action('button-click')} > {text("Label", "Hello Storybook")}</PrimaryButton>
  </Story>
</Preview>

This generate doc as below : enter image description here There is a show code/ hide code switch which shows the React Code for the component , is it possible to show the plain HTML markup as well.

I need to use a single storybook component explorer for React and non React Projects so wanted to check if plain markup source code be generated as well.

Thanks

like image 556
Bhupendra Avatar asked Oct 27 '25 04:10

Bhupendra


1 Answers

I am in a similar situation where I just want to use react for the development of the stories and only display the HTML in the docs so it can be used with other frameworks.

This is what I came up with so far.

In .storybook/preview.js I am using a custom function to render the source code so the file look something like this:

import renderToHTML from './renderToHTML'

export const parameters = {
  actions: { argTypesRegex: '^on[A-Z].*' },
  docs: {
    transformSource: (src, storyContext) => renderToHTML(storyContext.storyFn),
  },
}

this is documented here.

My renderToHTML function is defined like this:

import { renderToStaticMarkup } from 'react-dom/server'
import { AllHtmlEntities } from 'html-entities'
import prettier from 'prettier'
import HTMLParser from 'prettier/parser-html'
const entities = new AllHtmlEntities()

export default (story) =>
  prettier.format(entities.decode(renderToStaticMarkup(story())), {
    parser: 'html',
    plugins: [HTMLParser],
  })

I'm using renderToStaticMarkup to compile the story, then html-entities to unescape it and then using prettier to format it.

I am still experimenting with this so I might update the answer if I found issues or a better way to do things

like image 155
TedMeftah Avatar answered Oct 30 '25 13:10

TedMeftah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!