I just started using Material UI 5.0.4 (with styled-components
), and I wanted to access the theme in a component. I looked online and saw useTheme
, so I checked the docs and found it - @mui/styles/useTheme
. However, it was the legacy documentation, and @mui/styles
does not exist in MUI 5. So, I looked at @mui/system
instead, and found the section "Accessing the theme in a component". However, this just points back to the legacy documentation!
After the docs didn't seem to help me, I decided to use Visual Studio Code's "Quick Fix" feature, where if you hover over the function, VSCode will give you a list of options to import. Here is the list of options I tried, and why they didn't work:
@mui/material/styles/useTheme
- Returns the default theme object, no matter what. Looking into the source code, this is literally what it does - it switches to the default theme, and then returns the theme.@mui/material/private-theming/useTheme
- This just returnsnull
. I feel like I shouldn't be accessing this anyway (it saysprivate-
), but I tried it anyway.@mui/system/useTheme
- This is what I was hoping would work. However, this is also probably the weirdest one. It gives me the default theme, but it excludes many properties. For example, it only providedpalette.mode
, and there are no other keys underpalette
than that. (You can see the whole thing below)
{
"breakpoints": {
"keys": ["xs", "sm", "md", "lg", "xl"],
"values": { "xs": 0, "sm": 600, "md": 900, "lg": 1200, "xl": 1536 },
"unit": "px"
},
"direction": "ltr",
"components": {},
"palette": { "mode": "light" },
"shape": { "borderRadius": 4 }
}
styled-components/useTheme
- Returnsundefined
.@mui/styled-engine-sc/useTheme
- Returnsundefined
. (I have a feeling this is the same thing asstyled-components/useTheme
.)
Those were all the suggestions that VSCode could give me, apart from things like @mui/system/useTheme
vs @mui/system/useTheme/useTheme
(which is the same thing). I also tried googling stuff but it would always be really old, like:
- Issue #8958 on GitHub for MUI which references
@material-ui/core/styles
which is v4 and not in v5 - SO question labelled "access the theme from outside material-ui component" which references the legacy docs (
@material-ui/styles
does not exist anymore, and@mui/material/styles/useTheme
does not work as explained above)
Please, if someone knows, how do you get the theme in a component in MUI 5?
@mui/material/styles/useTheme
is the correct one to use. It only returns the default theme if you haven't specified a different one via@mui/material/styles/ThemeProvider
. – Sandy@mui/material/styles/ThemeProvider
... Let me make my question more clear with that. I'll also try to add a MRE – FousheeuseTheme
working: codesandbox.io/s/usetheme-example-bbule?file=/src/App.js. – SandyuseTheme
in the same component that theThemeProvider
is in. Once I made a new component, it worked perfectly fine. Thanks for your example! – Foushee