Storybook: How to set <body> classes?

Created on 17 Aug 2017  路  8Comments  路  Source: storybookjs/storybook

Hello!
Is there way to set <body> (inside <iframe>) class(es)? (except using finddomnode)
Thank you

react has workaround question / support

Most helpful comment

you can add file config.js to .storybook dir with something likes this:

import { configure } from '@storybook/react'

function loadStories () {
  document.body.className += ' ' + 'hasHover'
}

configure(loadStories, module)

All 8 comments

What are you trying to insert? You should generally be using stories to insert components and add decorators to them if you want the components to be wrapped in something.

Extremely hacky workaround: you can target the nodes onload with a script in the header
https://storybook.js.org/configurations/add-custom-head-tags/

I have add body tag with class attribute in the manager-head.html but it sets same for all stories while I need for different stories different body class(es).

Write a wrapper component / decorator that sets the classes for you.

Alternatively you could write an addon so you can change the class from a panel for example.

@ndelangen How do you set wrapper decorators with angular story books... I'm totally unable to do so.

you can add file config.js to .storybook dir with something likes this:

import { configure } from '@storybook/react'

function loadStories () {
  document.body.className += ' ' + 'hasHover'
}

configure(loadStories, module)

That will work, mind that config.js CAN be MHR, and so the code may execute multiple times.
Another way wuld be to do this in an addon, which rejects HMR or in preview-head.html.


storiesOf('name', module)
  .addDecorator(story => {
    document.body.classList.add('hasHover');
    return story();
  })
  .add('other name', () => {
    // ..
  });

Something like that might work, as a decorator.
But please consider that this will add a class to the body every time the story is rendered, and never cleans-up.. pretty bad.

Decorators are to change the story before they render, wrap them, extract data etc.

For permanent things side effects you're way better off using preview-head.html right now.

Creating a file named preview-head.html in your config directory containing this seems to have worked out for me.

Check the documentation here : https://storybook.js.org/configurations/add-custom-head-tags/

Was this page helpful?
0 / 5 - 0 ratings

Related issues

miljan-aleksic picture miljan-aleksic  路  3Comments

rpersaud picture rpersaud  路  3Comments

purplecones picture purplecones  路  3Comments

tlrobinson picture tlrobinson  路  3Comments

tirli picture tirli  路  3Comments