Search code examples
reactjsmaterial-ui

MUI ThemeProvider is not injecting theme in a compiled component


So I have these two projects that use MUI. One of them contains only small functional components (a library) and the other imports the "library" of components via yarn link, and is supposed to apply a custom theme via the "ThemeProvider".

I use storybook for my list of components. In order to see that all works as expected I use storybook's plugin: 'storybook-addon-material-ui'.

Example code of how I define my stories:

storiesOf('Tile', module)
  .addDecorator(muiTheme([myCustomTheme]))
  .add('Default', withInfo()(() => (
    <div>
      <Tile title="Title goes here" />
    </div>
  )))

Storybook shows the exact results I want. My custom theme is also exported from the Library project. When I use it in my Work Project (the one that imports the library), I define the Theme via import { ThemeProvider as MuiThemeProvider } from '@material-ui/core/styles'; in the first possible wrapping component:

class Layout extends Component {
  render() {
    return (
      <MuiThemeProvider theme={theme}>
         // Provider, Routing, etc
      </MuiThemeProvider>
    )
  }

}

The result: every single MUI component in my work project EXCEPT my library components is styled in my custom theme. However my custom components are styled in the base MUI theme that comes in core.

When I use the components they are already build with the script:

BABEL_ENV=production babel src -d lib --ignore src/**/*.story.jsx,src/**/*.spec.js,src/**/*.test.js

Am I missing some setting I need to give my custom components, so that they use the Theme provided my MUI?


Solution

  • So this turned out to be the same bad behaviour that is observed in this very common issue: https://github.com/facebook/react/issues/13991. In my case, I had two instances of Material UI because of yarn link. I solved it by creating alias in my webpack:

    config.resolve = {
      ...config.resolve,
      alias: {
        react: path.resolve("./node_modules/react"),
        '@material-ui': path.resolve("./node_modules/@material-ui")
      }
    };