Search code examples
reactjsmaterial-uithemeprovider

Style MUI component but have it's style overwritten by passed ThemeProvider


I want to style my custom React/MUI components by default, but still have the parent MUI ThemeProvider be able to override my styles.

For example, let's say that I have a Button that is green by default (styled in my code), but it should be able to have the colour overridden by a default theme passed down via ThemeProvider.

I can't seem to find anyway to do it as any styling I apply in my component becomes the default as it's the last in the CSS/styling tree.


Solution

  • I couldn't find much information in the documention or github issues about that topic — I can just tell you how to cope with the situation and how it works currently in v5.

    It seems like the priority is as follows:

    sx > styled() > theme

    ie. sx has the highest priority.

    At first it seems quite strange that you cannot overwrite something with your theme, but on the other hand you'd also like to be able to overwrite the theme with sx occasionally. So to me the priority makes sense.

    You should not use !important in the theme if possible, because it prevents sx and styled() from doing its job.

    What you'd do is ship reusable components unstyled (no styled() or sx) and style them via the theme.

    Perform the colorization in the theme. Width, height, margins and paddings you can also define via styled() and/or sx if you don't need to change those in the theme.