Storybook: How to add theme and global style for Documentation-only MDX

Created on 22 Aug 2020  路  5Comments  路  Source: storybookjs/storybook

I'm having trouble applying theme and global styles from styled-components for Documentation-only MDX. I followed the instruction written here to create a Documentation-only MDX. The problems is that since I don't use to wrap around my components, I can't seem to apply the global styles using decorators.

Here is what I have to set decorators:

export const decorators = [
    Story => (
        <ThemeProvider theme={theme}>
            <GlobalStyle />
            <div style={{ backgroundColor: "#000" }}>
                <Story />
            </div>
        </ThemeProvider>
    ),
];

and here is an example of my component in MDX:

<Canvas>
    <Heading variant="h2">H2 Heading</Heading>
</Canvas>

The global styles does get applied if I write:

<Canvas>
    <Story name="h2">
        <Heading variant="h2">H2 Heading</Heading>
    </Story>
</Canvas>

Is there anyway to apply the theme and global style without having the tag?

docs question / support theming

All 5 comments

@shilman Thank you for the quick response! I see that this would require me to write the code for every story that I have. Is there a way to apply it globally?

Sure. You can export parameters globally from .storybook/preview.js

export const parameters = { docs: { container: .... } }

https://storybook.js.org/docs/react/writing-stories/parameters#global-parameters

@shilman Ah that makes sense! Thank you very much! I will close this because my question has been answered.

For those who might be wondering how it is achieved at the end, here is my example:

import React from "react";
import { DocsContainer } from "@storybook/addon-docs/blocks";
import { ThemeProvider } from "styled-components";
import { GlobalStyle } from "../lib/utils/global";
import { theme } from "../lib/utils/theme";
import "normalize.css";

export const parameters = {
    docs: {
        container: ({ children, context }) => (
            <DocsContainer context={context}>
                <ThemeProvider theme={theme}>
                    <GlobalStyle />
                    {children}
                </ThemeProvider>
            </DocsContainer>
        ),
    },
};
Was this page helpful?
0 / 5 - 0 ratings

Related issues

MrOrz picture MrOrz  路  3Comments

dnlsandiego picture dnlsandiego  路  3Comments

purplecones picture purplecones  路  3Comments

miljan-aleksic picture miljan-aleksic  路  3Comments

sakulstra picture sakulstra  路  3Comments