Skip to content
Advertisement

material-ui : enable the dark mode automatically

As per the documentation:

It says dark mode theme will be generated automatically and get reflected in UI, but it is not working for me.

Dependencies:
    "@emotion/styled": "^11.0.0",
    "@material-ui/core": "^5.0.0-alpha.16",
    "@material-ui/icons": "^5.0.0-alpha.15",
    "@material-ui/lab": "^5.0.0-alpha.16",

Code:

import { createMuiTheme } from "@material-ui/core/styles";
import { CssBaseline, ThemeProvider, useMediaQuery } from "@material-ui/core";
import { green, purple } from "@material-ui/core/colors";
import { useEffect, useMemo } from "react";
import { Route, Switch, useHistory } from "react-router-dom";
import SignIn from "./ui/auth/SignIn.js";
import SignUp from "./ui/auth/SignUp.js";
import Welcome from "./ui/auth/Welcome.js";
import { log } from "./util/logger.js";

const App = () => {

  const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)');

  const theme = useMemo(
    () => {

      log(prefersDarkMode, "Dark Mode");

      const themeOptions = {
        palette: {
          type: prefersDarkMode ? 'dark' : 'light',
          primary: purple,
          secondary: green
        },
      }

      log(JSON.stringify(themeOptions), "Theme Option")

      const theme = createMuiTheme(themeOptions);

      log(theme, "Theme");

      return theme;
    },
    [prefersDarkMode],
  );

  const history = useHistory()

  useEffect(() => {
    const timer = setTimeout(() => {
      history.push("/signin");
    }, 3000);

    return function cleanup() {
      clearTimeout(timer);
    };
  });

  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <Switch>
        <Route path="/" component={Welcome} exact />
        <Route path="/signin" component={SignIn} />
        <Route path="/signup" component={SignUp} />
      </Switch>
    </ThemeProvider>
  );
}

export default App;

Signup.js

import React, { useState } from 'react';
import Avatar from '@material-ui/core/Avatar';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';
import Link from '@material-ui/core/Link';
import Grid from '@material-ui/core/Grid';
import Box from '@material-ui/core/Box';
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/core/styles';
import Container from '@material-ui/core/Container';
import ForgotPassword from './ForgotPassword';
import { useHistory } from 'react-router-dom';

const Copyright = () => {
    return (
        <Typography variant="body2" color="textSecondary" align="center">
            {'Copyright © '}
            <Link color="inherit" href="https://material-ui.com/">
                Your Website
            </Link>
            {' '}
            {new Date().getFullYear()}
            {'.'}
        </Typography>
    );
}

const useStyles = makeStyles((theme) => ({
    paper: {
        marginTop: theme.spacing(8),
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        background: theme.palette.background.default
    },
    avatar: {
        margin: theme.spacing(1),
        backgroundColor: theme.palette.secondary.main,
    },
    form: {
        width: '100%', // Fix IE 11 issue.
        marginTop: theme.spacing(1),
    },
    submit: {
        margin: theme.spacing(3, 0, 2),
    },
}));

const SignIn = () => {

    const classes = useStyles();
    const history = useHistory();

    // Forgot Password State
    const [open, setOpen] = useState(false);
    function openForgotPassword(event) {
        event.preventDefault();
        setOpen(true);
    }

    function onClose() {
        setOpen(false);
    }

    function goToSignUp(event) {
        event.preventDefault();
        history.push('/signup');
    }

    return (
        <Container component="main" maxWidth="xs">
            <div className={classes.paper}>
                <Avatar className={classes.avatar}>
                    <LockOutlinedIcon />
                </Avatar>
                <Typography component="h1" variant="h5">
                    Sign in
                </Typography>
                <form className={classes.form} noValidate>
                    <TextField
                        variant="outlined"
                        margin="normal"
                        required
                        fullWidth
                        id="email"
                        label="Email Address"
                        name="email"
                        autoComplete="email"
                        autoFocus
                    />
                    <TextField
                        variant="outlined"
                        margin="normal"
                        required
                        fullWidth
                        name="password"
                        label="Password"
                        type="password"
                        id="password"
                        autoComplete="current-password"
                    />
                    <FormControlLabel
                        control={<Checkbox value="remember" color="primary" />}
                        label="Remember me"
                    />
                    <Button
                        type="submit"
                        fullWidth
                        variant="contained"
                        color="primary"
                        className={classes.submit}
                    >
                        Sign In
                    </Button>
                    <Grid container>
                        <Grid item xs>
                            <Link href="#" onClick={openForgotPassword} variant="body2">
                                Forgot password?
                            </Link>
                        </Grid>
                        <Grid item>
                            <Link href="#" onClick={goToSignUp} variant="body2">
                                {"Don't have an account? Sign Up"}
                            </Link>
                        </Grid>
                    </Grid>
                </form>
            </div>
            <Box mt={8}>
                <Copyright />
            </Box>
            <ForgotPassword open={open} onClose={onClose} />
        </Container>
    );
}

export default SignIn;

Background is not getting dark with the type. Can someone help with this?

Advertisement

Answer

My bad. The latest version of Material UI now uses mode attribute of palette to determine whether dark mode or not. Simply change from ‘type’ to ‘mode’:

  // Enabling Dark Mode according to system-wide setting
  const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
  const theme = useMemo(
    () => createMuiTheme({
      palette: {
        mode: prefersDarkMode ? 'dark' : 'light',
        primary: purple,
        secondary: green
      },
    }),
    [prefersDarkMode],
  );

Complete code of App.js:

import { createMuiTheme, CssBaseline, ThemeProvider, useMediaQuery } from "@material-ui/core";
import { green, purple } from "@material-ui/core/colors";
import { useEffect, useMemo } from "react";
import { Route, Switch, useHistory } from "react-router-dom";
import SignIn from "./ui/auth/SignIn.js";
import SignUp from "./ui/auth/SignUp.js";
import Welcome from "./ui/auth/Welcome.js";

const App = () => {

  // Enabling Dark Mode according to system-wide setting
  const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
  const theme = useMemo(
    () => createMuiTheme({
      palette: {
        mode: prefersDarkMode ? 'dark' : 'light',
        primary: purple,
        secondary: green
      },
    }),
    [prefersDarkMode],
  );

  const history = useHistory()
  useEffect(() => {
    // After displaying Welcome screen for 3 seconds
    // go to SignIn page
    const timer = setTimeout(() => {
      history.push("/signin");
    }, 3000);

    return function cleanup() {
      clearTimeout(timer);
    };
  });

  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <Switch>
        <Route path="/" component={Welcome} exact />
        <Route path="/signin" component={SignIn} />
        <Route path="/signup" component={SignUp} />
      </Switch>
    </ThemeProvider>
  );
}

export default App;
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement