1

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.

Roo
  • 259
  • 1
  • 3
  • 15
  • 1
    How are you styling your components? Is it with a css/scss file? Or using the style object provided by MUI? – Ary Barros Jul 07 '22 at 13:24
  • 1
    I've tried using the MUI styled object, applying a class and using the style/sx props - all of these take precedence over the ThemeProvider. – Roo Jul 07 '22 at 13:29
  • Your theme provider has a theme attribute? https://styled-components.com/docs/advanced – Ary Barros Jul 07 '22 at 13:33
  • It is very unfortunate, that this question has no answer, because it actually a very fundamental topic in regards to material-ui! Have you figured it out what's the best solution or do you use !important in the theme etc.? Thanks. – Ini Feb 06 '23 at 16:00

1 Answers1

0

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.

Ini
  • 548
  • 7
  • 19