#Issues with MUI Theming

41 messages · Page 1 of 1 (latest)

soft moat
#

Hi There,
I've been having some issue with using our custom MUI theme in stories. I've read through several of the existing threads on this issue but am still struggling to find a solution. This is how we initially used our theme in stories:

// preview.tsx
const preview: Preview = {
  decorators: [
    (Story) => (
      <DefaultThemeProvider>
       <Story />
      </DefaultThemeProvider>
    ),
    ...

Where DefaultThemeProvider is exported from an internal dependency that contains a wrapped version of MUI

export const DefaultThemeProvider: FC<React.PropsWithChildren> = ({ children }) => (
  <ThemeProvider theme={theme}>{children}</ThemeProvider>
);

This was working great. However, I added a component to storybook with the following dependency on MUI break points:

height: { md: "62vh", lg: "70vh", xl: "75vh" },

Unfortunately this component renders with no height applied.

I then tried using the @storybook/addon-styling add-on:

import { theme } from "@our-library";
import { withThemeFromJSXProvider } from "@storybook/addon-styling";
import { CssBaseline, ThemeProvider } from "@mui/material";

const preview: Preview = {
  decorators: [
    (Story) => (
      <Story />
    ),
    //@ts-ignore
    withThemeFromJSXProvider({
      themes: {
        default: theme,
      },
      defaultTheme: "default",
      Provider: ThemeProvider,
      GlobalStyles: CssBaseline,
    }),
  ],
  ...

This respects the height logic but our custom theme is not applied. Perhaps the TS error is a clue?

Types of property 'component' are incompatible.
Type 'unknown' is not assignable to type 'ComponentType<any> | undefined'.ts(2322)

Here are some of the relevant dependencies:

"@storybook/addon-styling": "1.3.4",
"storybook": "7.0.26",
"vite": "4.1.5",

Thanks in advance for your help!

lyric comet
#

Hey @soft moat I'm the author of addon-styling 😄 Hopefully I can help

#

Can you share with me how you defined your theme?

#

Also, can I see your main.ts?

soft moat
#

@lyric comet thanks for the quick reply!
Here is how we are defining our theme:

import { createTheme } from "@mui/material";
import {
  muiAutoCompleteTheme,
  muiButtonTheme,
  ...
} from "./components";

export const theme = createTheme(
  muiAutoCompleteTheme,
  muiButtonTheme,
  ...
);

Where muiButtonTheme etc. is defined as:

import { ThemeOptions } from "@mui/material";

export const muiButtonTheme: ThemeOptions = {
  components: {
    MuiButton: {
      defaultProps: {
        variant: "contained",
      },
    },
  },
};

main.ts

import type { StorybookConfig } from "@storybook/react-vite";
import { mergeConfig } from "vite";
import macrosPlugin from "vite-plugin-babel-macros";

process.env.JEST_JUNIT_OUTPUT_DIR = "reports/storybook";

export default {
  addons: [
    "@storybook/addon-a11y",
    "@storybook/addon-coverage",
    "@storybook/addon-essentials",
    "@storybook/addon-interactions",
    "@storybook/addon-links",
    "storybook-addon-pseudo-states",
    "@storybook/addon-storysource",
  ],
  core: { builder: "@storybook/builder-vite" },
  docs: { autodocs: true },
  framework: {
    name: "@storybook/react-vite",
    options: {},
  },
  stories: ["../src/**/*.stories.mdx", "../src/**/*.stories.@(js|jsx|ts|tsx)"],
  staticDirs: ["../public"],
  viteFinal: async (config) =>
    mergeConfig(config, {
      plugins: [macrosPlugin()],
      server: {
        port: 6006,
        strictPort: true,
        watch: {
          ignored: [
            "./.env",
            "./.env.*",
            "./coverage/**",
            "./cypress/**",
            "./dist/**",
            "./reports/**",
            "./storybook-static/**",
          ],
        },
      },
    }),
} satisfies StorybookConfig;

Thanks again!

lyric comet
#

Ahhh! Try adding @storybook/addon-styling to your addon array in main.ts with no options

soft moat
#

This is our default main.ts before adding @storybook/addon-styling. I definitely had it in the addons array when I tried it out.

Sorry for the confusion!

lyric comet
#

Hmmmm okay 🤔

soft moat
lyric comet
#

Do you have any errors in the browser?

soft moat
#

I don't remember seeing any but I will set it up again real quick and check it out.

#

Ok I'm all set up. Here are my addons:

  addons: [
    "@storybook/addon-a11y",
    "@storybook/addon-coverage",
    "@storybook/addon-essentials",
    "@storybook/addon-interactions",
    "@storybook/addon-links",
    "storybook-addon-pseudo-states",
    "@storybook/addon-storysource",
    "@storybook/addon-styling",
  ],

Here are my decorators:

import { theme } from "@my-stuff";
import { withThemeFromJSXProvider } from "@storybook/addon-styling";
import { CssBaseline, ThemeProvider } from "@mui/material";


  decorators: [
    mswDecorator,
    (Story) => (
      <ApolloMockingProvider>
        <Story />
      </ApolloMockingProvider>
    ),
    withThemeFromJSXProvider({
      themes: {
        default: theme,
      },
      defaultTheme: "theme",
      Provider: ThemeProvider,
      GlobalStyles: CssBaseline,
    }),
  ],

MUI isn't a direct dependency of this project but I installed it at some point and didn't notice any change.

There are no errors but there is a warning:

You are loading @emotion/react when it is already loaded. Running multiple instances may cause problems. This can happen if multiple versions are used, or if multiple builds of the same version are used.

This warning also appears in our app and we don't have any issues with theming there.

lyric comet
#

Yeah, that warning should be fine

#

Here’s a long shot…

#

In the decorator, can you change the name of the theme to something other than default?

#

I wonder if that’s causing a weird issue as a reserved keyword

soft moat
#

I like long shot ideas 🙂

Unfortunately not even uncle Bob helped 😦

      themes: {
        uncleBob: theme,
      },
      defaultTheme: "uncleBob",
lyric comet
#

Damn... okay

#

Can you share a reproduction codebase for me to dig around in?

#

you can use npx storybook@latest sandbox to spin something up

soft moat
#

Oh man, I'm not even sure what that would look like. Our MUI implementation is in a separate repo so the issue could also be there. I'll let you know if I can come up with something. Thanks for taking a look!

soft moat
#

I got a basic implementation work as instructed above. I then replaced the dependencies/resolutions with the ones in our MUI library and everything was still working. I then pasted on all of the dependencies/resolutions from our main app and deleted all of the copies. Now Storybook won' run so I think we are getting somewhere! I'll try to narrow down the dependency that is causing issues in the AM but here is a console error that looks promising:

The above error occurred in the <Styled(a)> component:

    at http://localhost:6006/node_modules/.cache/.vite-storybook/deps/chunk-SIAJBJVZ.js?v=ffd96cdd:1433:45
    at Link2 (http://localhost:6006/node_modules/.cache/.vite-storybook/deps/chunk-CK55VVE5.js?v=ffd96cdd:686:16)
    at div
    at http://localhost:6006/node_modules/.cache/.vite-storybook/deps/chunk-44SAWIY2.js?v=ffd96cdd:1442:45
    at EmptyBlock
    at ArgsTable (http://localhost:6006/node_modules/.cache/.vite-storybook/deps/chunk-75RHMGDY.js?v=ffd96cdd:976:15)
    at Controls3 (http://localhost:6006/node_modules/.cache/.vite-storybook/deps/chunk-75RHMGDY.js?v=ffd96cdd:1395:9)
    at DocsPage (http://localhost:6006/node_modules/.cache/.vite-storybook/deps/chunk-75RHMGDY.js?v=ffd96cdd:1591:20)
    at div
    at http://localhost:6006/node_modules/.cache/.vite-storybook/deps/chunk-44SAWIY2.js?v=ffd96cdd:1442:45
    at div
    at http://localhost:6006/node_modules/.cache/.vite-storybook/deps/chunk-44SAWIY2.js?v=ffd96cdd:1442:45
    at DocsPageWrapper (http://localhost:6006/node_modules/.cache/.vite-storybook/deps/chunk-75RHMGDY.js?v=ffd96cdd:146:26)
    at ThemeProvider (http://localhost:6006/node_modules/.cache/.vite-storybook/deps/chunk-44SAWIY2.js?v=ffd96cdd:1468:44)
    at SourceContainer (http://localhost:6006/node_modules/.cache/.vite-storybook/deps/chunk-75RHMGDY.js?v=ffd96cdd:1200:26)
    at DocsContainer (http://localhost:6006/node_modules/.cache/.vite-storybook/deps/chunk-75RHMGDY.js?v=ffd96cdd:1531:24)
lyric comet
#

Are you using pnpm or yarn pnp by any chance?

soft moat
#

We aren't using either of them directly but pnpm is being used by semantic-release which is a dependency and is showing up in our yarn.lock. I just tried removing it and am seeing the same errors when I try to load Storybook. I'll keep going through the dependencies and let you know if I find anything.

soft moat
#

I just went through all of the dependencies systematically and, while I could replicate the loading error when I started, I can't replicate the loading error now. I'm really not sure what else to try. There are just so many potential factors. I'll keep thinking about it though.

soft moat
#

I've been over thinking this. I setup a small theme in my App and when I use that it is applied properly. The theme imported from our other repo still doesn't work. So what's the difference?

#

Local theme

#

Our custom imported theme

#

Would the lack of unstable_sx and/or unstable_sxConfig cause our theme to be ignored?

#

There is also no prototype on our MuiButton object

#

Vs the local version

#

The plot thickens. I added palette to my local theme and the colors are not getting applied:

export const muiButtonTheme: ThemeOptions = {
  components: {
    MuiButton: {
      defaultProps: {
        color: "secondary",
        variant: "contained",
      },
    },
  },
  palette: {
    primary: {
      main: "#3B75D1",
      dark: "#1E4C94",
      light: "#91B3EB",
    },
    secondary: {
      main: "#0B8484",
      dark: "#045C5C",
      light: "#60D1D1",
    },
  },
};
soft moat
#

I replicated the structure of how we set up our custom theme locally in the test repo and the theme is not getting applied. I'll share the repo shortly.

lyric comet
#

This is a curious problem you have here!

lyric comet
#

@soft moat How should I boot up SB in your repro? The root package.json isn't set up for workspaces

soft moat
#

From the default-ts directory you should be able to run yarn install then yarn storybook. There is a nested directory structure which comes from the npx storybook@latest sandbox command.

#

I was looking through your source code yesterday and it looks like you are just passing the given theme to the given provider right?

<Provider theme={theme}>
  {GlobalStyles && <GlobalStyles />}
  {storyFn()}
</Provider>

It seems unlikely this is causing my issue but you know your code way better than I do.
I was also looking through the MUI createTheme function but I haven't quite wrapped my head around it yet:
https://github.com/mui/material-ui/blob/97de680ba34102667f4f7c497a596c518daeaacc/packages/mui-material/src/styles/createTheme.js#L16

GitHub

MUI Core: Ready-to-use foundational React components, free forever. It includes Material UI, which implements Google's Material Design. - mui/material-ui

lucid sphinx
lyric comet
#

@lucid sphinx That's sepcific to docs pages, OP is haing troubles getting their stories to work

#

@soft moat oh okay, is your project a monorepo?

#

I ask because I've run your reproduction and it seems to work from what I can tell