Reputation: 137
I'm using @material-ui/core to handle theming in my React app, but for some reason some of the styles are not being applied.
Here's my sandbox will the full code (relevant snippets below).
I followed the example in Material UI's docs but it doesn't seem to work.
The interesting thing is that the text does align center (which I specified in my styles), but the background color stays the default #fafafa
instead of #424242
as specified in my theme. So I guess the styles are being applied but my theme is not being applied to the styles.
Another weird thing is that I logged out the value of theme.palette.background.default
within the makeStyles
callback and it was #424242
.
Also, if I set the value of backgroundColor
in the useStyles
hook to a static string like #f00
, it does apply (the background color changes to red).
useStyles hook:
const useStyles = makeStyles(
(theme: Theme) =>
createStyles({
root: {
backgroundColor: theme.palette.background.default,
height: "100%",
textAlign: "center",
width: "100%"
}
}),
{ name: "App" }
);
App component:
const App = () => {
const classes = useStyles();
return (
<>
<CssBaseline />
<ThemeProvider theme={darkTheme}>
<div className={classes.root}>hello</div>
</ThemeProvider>
</>
);
};
Theme
// NOTE: gray[800] = #424242
export const darkTheme = createTheme({
palette: { background: { default: grey[800] } }
});
Upvotes: 2
Views: 5707
Reputation: 386
I also got it to work by updating your makeStyles from using
createStyles({
root: {
backgroundColor: theme.palette.background.default,
to:
createStyles({
root: {
backgroundColor: darkTheme.palette.primary.main,
and changed darkTheme.ts
to follow their keywords:
palette: {
primary: { main: grey[800] }
}
Here is the updated codesandbox: https://codesandbox.io/s/fancy-tdd-p35ld?file=/src/App.tsx
Upvotes: 0
Reputation: 80976
App
(and therefore your useStyles
call) is outside of the element hierarchy impacted by your dark theme ThemeProvider
. If you pull your div into its own component and call useStyles
from there, it works fine.
import React from "react";
import CssBaseline from "@material-ui/core/CssBaseline";
import {
makeStyles,
createStyles,
Theme,
ThemeProvider
} from "@material-ui/core/styles";
import { darkTheme } from "./DarkTheme";
const useStyles = makeStyles(
(theme: Theme) =>
createStyles({
root: {
backgroundColor: theme.palette.background.default,
height: "100%",
textAlign: "center",
width: "100%"
}
}),
{ name: "App" }
);
const Hello = () => {
const classes = useStyles();
return <div className={classes.root}>hello</div>;
};
const App = () => {
return (
<>
<CssBaseline />
<ThemeProvider theme={darkTheme}>
<Hello />
</ThemeProvider>
</>
);
};
export default App;
Upvotes: 3