6

I want to create certain conditions based on whether the type of material ui theme is light or dark How can I do that?

jepbura
  • 372
  • 1
  • 6
  • 16

2 Answers2

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

Edit 64557510/how-can-i-check-the-type-of-material-ui-theme-in-react-js-light-or-dark

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