I want to create certain conditions based on whether the type of material ui theme is light or dark How can I do that?
I want to create certain conditions based on whether the type of material ui theme is light or dark How can I do that?
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
const isDarkTheme = useTheme().palette.type === 'dark';
const ThemedComponent = withTheme(Component)
render() {
const isDarkTheme = this.props.theme.palette.type === 'dark';
return (...)
}
The following does not work anymore:
const isDarkTheme = useTheme().palette.type === 'dark';
Try this Instead:
const isDarkTheme = useTheme().palette.mode === 'dark';