I want to create certain conditions based on whether the type of material ui theme is light or dark How can I do that?
Asked
Active
Viewed 3,469 times
2 Answers
8
You need to recreate the theme and update the value theme.palette.type
('light'
or 'dark'
) and pass it to the ThemeProvider
to apply the change.
const defaultTheme = createMuiTheme({
palette: {
type: "light"
}
});
function App() {
const [theme, setTheme] = React.useState(defaultTheme);
const onClick = () => {
const isDark = theme.palette.type === "dark";
setTheme(
createMuiTheme({
palette: {
type: isDark ? "light" : "dark"
}
})
);
};
return (
<ThemeProvider theme={theme}>
<Card>
<Typography variant="h3">{theme.palette.type}</Typography>
<Button onClick={onClick}>Toggle theme</Button>
</Card>
</ThemeProvider>
);
}
You can then check the theme type in children components using either hook or HOC
Hook
const isDarkTheme = useTheme().palette.type === 'dark';
HOC
const ThemedComponent = withTheme(Component)
render() {
const isDarkTheme = this.props.theme.palette.type === 'dark';
return (...)
}
Live Demo

NearHuscarl
- 66,950
- 18
- 261
- 230
5
The following does not work anymore:
const isDarkTheme = useTheme().palette.type === 'dark';
Try this Instead:
const isDarkTheme = useTheme().palette.mode === 'dark';

paradus-hex
- 221
- 2
- 6
-
Checking the mode works for me, thank you – utopia Jun 27 '23 at 08:49