hipstersmoothie / storybook-dark-mode

A storybook addon that lets your users toggle between dark and light mode.
MIT License
429 stars 56 forks source link

Light/dark mode not working on first load Storybook v7 #230

Open Elvissamir opened 1 year ago

Elvissamir commented 1 year ago

I'm trying to use this awesome plugin with storybook 7, but unfortunately the light/dark theme mode is not applied on the first load. Even if I refresh the page, the light theme is not applied as specified in the darkMode property.

This is the configuration in preview.tsx: parameters: { darkMode: { light: lightTheme, dark: darkTheme, current: "light", stylePreview: true }, actions: { argTypesRegex: "^on[A-Z].*" }, controls: { matchers: { color: /(background|color)$/i, date: /Date$/, }, }, },

If I click on any of the stories the theme changes, and works as expected.

I'm using storybook v7.0.0-rc.1 and storybook-dark-mode v2.1.1

trajano commented 1 year ago

Tried it myself

const preview: Preview = {
  parameters: {
    actions: { argTypesRegex: '^on[A-Z].*' },
    controls: {
      matchers: {
        color: /(background|color)$/i,
        date: /Date$/
      }
    },
    darkMode: {
      darkClass: 'mode--dark',
      lightClass: 'mode--light',
      classTarget: 'html',
    }
  }
}

But nothing seems to get applied when I inspect the body or html.

KevinVandy commented 1 year ago

I had to use this to get it to work in the preview.tsx file, decorators

      const defaultTheme = useDarkMode() ? darkTheme : lightTheme;

      useEffect(() => {
        const sbRoot = document.getElementsByClassName(
          'sb-show-main',
        )[0] as HTMLElement;
        if (sbRoot) {
          sbRoot.style.backgroundColor = defaultTheme.palette.background.paper;
        }
      }, [useDarkMode()]);