Saturday, November 23, 2024
Google search engine
HomeLanguagesJavascriptHow to create Dark Mode in ReactJS using Material UI ?

How to create Dark Mode in ReactJS using Material UI ?

In recent years, dark mode has become a popular feature in many applications and websites. It offers a visually appealing and more comfortable viewing experience, especially in low-light conditions. If you’re working with ReactJS and Material UI, you can easily implement dark mode functionality in your application. In this article, you will learn how to add a dark mode switch in your React web app to toggle between light and dark mode.

Step for Creating React Application And Installing Module:

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. folder name, move to it using the following command:

cd foldername

Step 3: After creating the React.js application, install the material-UI modules using the following command.

npm install @material-ui/core
npm install @material-ui/icons

Example: After creating a basic to react app, we will make changes in App. js as follows :

Step 1: Import ThemeProvider and createMuiTheme

import { createMuiTheme, ThemeProvider } from '@material-ui/core/styles';

Step 2: Set up the toggle logic in App.js

const [toggleDark, settoggleDark] = useState(false);
const myTheme=createMuiTheme({

    // Theme settings
    palette:{
          type: toggleDark ? 'dark' : 'light',
    }
});

Step 3: Here I am creating a new SmallComponent which will be our new component imported in App. j (You can customize it to your own component. Here I am focusing on implementing dark mode in already existing code). Pass the states for dark mode (toggle dark and settoggleDark), which will be used to switch between light and dark mode. Wrap up your component inside the ThemeProvider and pass your customized theme.

<ThemeProvider theme={myTheme}>
    <SmallComponent toggleDark={toggleDark} settoggleDark={settoggleDark}/>
</ThemeProvider>

Step 4: Trigger toggle using onChange Switch in SmallComponent.js

const handleModeChange = () => {
    settoggleDark(!toggleDark)
};
<Switch
    checked={toggleDark}
    onChange={handleModeChange}
    name="toggleDark"
    color="default"
/>

Example: 

App.js

Javascript




import React, { useState } from "react";
import SmallComponent from "./SmallComponent";
import { createMuiTheme, ThemeProvider } from "@material-ui/core/styles";
 
function App() {
    const [toggleDark, settoggleDark] = useState(false);
    const myTheme = createMuiTheme({
 
        // Theme settings
        palette: {
            type: toggleDark ? "dark" : "light",
        },
    });
 
    return (
 
        // Wrapping code in ThemeProvider
        <ThemeProvider theme={myTheme}>
            <SmallComponent toggleDark={toggleDark}
                settoggleDark={settoggleDark} />
        </ThemeProvider>
    );
}
 
export default App;


SmallComponent.js

Javascript




import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Card from "@material-ui/core/Card";
import CardHeader from "@material-ui/core/CardHeader";
import CardMedia from "@material-ui/core/CardMedia";
import CardContent from "@material-ui/core/CardContent";
import CardActions from "@material-ui/core/CardActions";
import Avatar from "@material-ui/core/Avatar";
import IconButton from "@material-ui/core/IconButton";
import Typography from "@material-ui/core/Typography";
import { red } from "@material-ui/core/colors";
import FavoriteIcon from "@material-ui/icons/Favorite";
import ShareIcon from "@material-ui/icons/Share";
import Grid from "@material-ui/core/Grid";
import MoreVertIcon from "@material-ui/icons/MoreVert";
 
// Import your profile image in images folder
import myImg from "./images/nikita-img.jpeg";
 
// Import your background image in images folder
import backImg2 from "./images/nik2.jpg";
import Switch from "@material-ui/core/Switch";
 
const useStyles = makeStyles((theme) => ({
 
    // Styling material components
    root: {
        width: "100%",
        height: "100vh",
        backgroundColor: theme.palette.background.default,
        [theme.breakpoints.down("xs")]: {
            paddingTop: theme.spacing(2),
        },
    },
    media: {
        height: 56,
        paddingTop: "56.25%", // 16:9
    },
    avatar: {
        backgroundColor: red[500],
    },
}));
 
export default function SmallComponent({
    toggleDark, settoggleDark }) {
    const classes = useStyles();
 
    // Trigger toggle using onChange Switch
    const handleModeChange = () => {
        settoggleDark(!toggleDark);
    };
    return (
        <Grid
            className={classes.root}
            container
            justify="center"
            alignItems="center"
        >
            <Card elevation={8}>
                {/* you can modify the image avatar,
         background and title name to yours*/}
                <CardHeader
                    avatar={<Avatar alt="Nikita Chaudhari" src={myImg} />}
                    action={
                        <IconButton aria-label="settings">
                            <MoreVertIcon />
                        </IconButton>
                    }
                    title="Nikita Pradip Chaudhari"
                    subheader="nikita12c"
                />
                <CardMedia
                    className={classes.media}
                    image={backImg2}
                    title="Paella dish"
                />
                <CardContent>
                    <Typography variant="body2" color="textSecondary"
                                component="p">
                        Geeks For Geeks : Dark Mode
                    </Typography>
                </CardContent>
                <CardActions disableSpacing>
                    <IconButton aria-label="add to favorites">
                        <FavoriteIcon />
                    </IconButton>
                    <IconButton aria-label="share">
                        <ShareIcon />
                    </IconButton>
                    {/* switching between dark and light mode */}
                    <Switch
                        checked={toggleDark}
                        onChange={handleModeChange}
                        name="toggleDark"
                        color="default"
                    />
                </CardActions>
            </Card>
        </Grid>
    );
}


See the demo video below: 

Explanation: Material-UI comes with two palette types; light (the default) and dark. You can make the theme dark by setting the type: ‘dark’. If you want more control of the color scheme, you can define them yourself, or you can visit https://material-ui.com/customization/color/#playground on Material-UI’s website to choose your desired color scheme. 

Reference: https://material-ui.com/customization/palette/

RELATED ARTICLES

Most Popular

Recent Comments