Implementing Dark and Light Theme in ReactJS: A Step-by-Step Guide

  • react-js
  • 126 Views
  • 4 Min Read
  • 8 Jul 2024

Hello developers! Welcome to this article, where we'll show you how to add dark and light themes to your project using ReactJS.

 

React Dark/light mode theme

 

In the modern world of the internet, how users feel while using a website or app is most important. If we are giving them options, such as choosing between dark and light themes, it can help improve their experience. Adding these options to the website can make users happier and make it easier for everyone to use.

 

In this easy-to-follow guide, we'll show you step-by-step how to add dark and light themes to your ReactJS website using Material-UI.

 

 

Prerequisites

 

Before diving into the implementation, ensure you have the following:

 

  • Basic knowledge of ReactJS.
  • Familiarity with the Material-UI library.
  • Node.js is installed on your system.

 

 

Integrating Dark and Light Themes

 
In just 5 easy steps, I'll guide you through creating a React project with dark and light themes. We'll break it down step by step for a clear understanding.
 
  • Step 1: Setting Up the Project
  • Step 2: Installing Dependencies 
  • Step 3: Creating Components
  • Step 4: Implementing Dark and Light Themes
  • Step 5: Test Your Code

 

Step 1: Setting Up the Project

 
Start by creating a new ReactJS project. You can use create-react-app to set up the project quickly. Run the following command in your terminal:
 
npx create-react-app dark-light-theme-react
 

Step 2: Installing Dependencies

 

Next, install Material-UI and its related dependencies using npm or yarn.

 
// For npm
npm i @mui/material @emotion/react @emotion/styled @mui/icons-material

// For yarn
yarn add @mui/material @emotion/react @emotion/styled @mui/icons-material
 

Step 3: Creating Components

 

Navigate to the 'src' directory and create a 'components' folder. Within this folder, create three files: 'Navbar.jsx', 'MyComponent.jsx', and 'Footer.jsx'.

 

Navbar.jsx: 

 

A navigation bar component to toggle between dark and light themes.

 

// src/components/Navbar.jsx

import React from "react";
import { AppBar, Toolbar, IconButton } from "@mui/material";
import Brightness4Icon from '@mui/icons-material/Brightness4';
import Brightness7Icon from '@mui/icons-material/Brightness7';

const NavBar = ({ toggleDarkTheme, toggleDarkMode }) => {
    return (
        <AppBar position="static" color="primary">
            <Toolbar style={{ display: 'flex', justifyContent: 'space-between' }}>
                <h1>Theme Changer</h1>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                    <ul style={{ display: "flex", gap: '50px', listStyle: 'none', paddingRight: '20px' }}>
                        <li>Home</li>
                        <li>About</li>
                        <li>Project</li>
                        <li>Contact</li>
                    </ul>
                    <IconButton onClick={toggleDarkTheme} color="inherit">
                        {toggleDarkMode ? <Brightness7Icon /> : <Brightness4Icon />}
                    </IconButton>
                </div>
            </Toolbar>
        </AppBar >
    );
};

export default NavBar;
 

This code imports the necessary items and icons from Material-UI to create a NavBar component. The component switches between dark and light themes when users interact with the IconButton. The icon's color stays white because it's set to inherit. Also, we use a ternary operator to decide which icon to show based on the toggleDarkMode state.

 

MyComponent.jsx:

 

The user interface design elements are included in this component.

 
// src/components/MyComponent.jsx

import React from "react";
import { Card, CardMedia } from "@mui/material";

const MyComponent = () => {
    return (
        <div style={{ display: 'flex' }}>
            
            {/* Left Side */}
            <Card style={{ flex: 1, marginLeft: 10, display: 'grid', placeItems: 'center' }}>
                <div style={{ margin: '10px', }}>
                    <h1>Welcome to our site</h1>
                    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dignissimos corrupti dolore et quibusdam distinctio quaerat dolor laboriosam, ratione saepe nihil dolorem mollitia sapiente recusandae assumenda obcaecati ut voluptas ab praesentium.</p>
                </div>
            </Card>

            {/* Right Side */}
            <Card style={{ flex: 1, marginRight: 10 }}>
                <CardMedia
                    component="img"
                    image="https://images.pexels.com/photos/546819/pexels-photo-546819.jpeg"
                    alt="Semaphore"
                />
            </Card>
        </div>
    );
};

export default MyComponent;

 

In this code, we have created a component of React named MyComponent. It uses Material-UI's Card and CardMedia components to show content and an image. The component shows a title and text on the left and an image on the right using a flexbox layout.

 

Footer.jsx: 

 
// src/components/Footer.jsx

import React from "react";
import { Box } from "@mui/material";

const Footer = () => {
    return (
        <Box sx={{
            position: 'fixed',
            bottom: 0,
            width: '100%',
            display: "flex",
            justifyContent: 'center',
            padding: '20px',
        }}>
            Where creativity meets functionality – welcome to our project!😊
        </Box >
    );
};

export default Footer;
 

This code makes a React Footer using Material-UI's Box. It shows a footer at the bottom of the page with a message.

 

Step 4: Implementing Dark and Light Themes

 

In your App.js, import the necessary components and set up the theme toggle functionality using React's state management.

 
// App.js

import React, { useState } from "react";
import { ThemeProvider, createTheme } from "@mui/material/styles";
import CssBaseline from "@mui/material/CssBaseline";
import NavBar from "./components/Navbar";
import MyComponent from "./components/MyComponent";
import Footer from "./components/Footer";
import { Container } from "@mui/material";

export default function App() {
    const [toggleDarkMode, setToggleDarkMode] = useState(false);

    const toggleDarkTheme = () => {
        setToggleDarkMode(!toggleDarkMode);
    };

    const darkTheme = createTheme({
        palette: {
            mode: toggleDarkMode ? 'dark' : 'light',
            primary: {
                main: '#009bf5',
            },
        },
    });

    return (
        <ThemeProvider theme={darkTheme}>
            <CssBaseline />
            <NavBar toggleDarkTheme={toggleDarkTheme} toggleDarkMode={toggleDarkMode} />
            <Container maxWidth="md" sx={{ marginTop: 4 }}>
            </Container>
            <MyComponent />
            <Footer />
        </ThemeProvider>
    );
}
 

In the App.js file, we start by using the useState hook to manage the toggleDarkMode state, determining whether the application should display a dark or light theme.

 

The toggleDarkTheme function then enables smooth switching between these themes, updating the toggleDarkMode state accordingly.

 

Next, we define a darkTheme object using Material-UI's createTheme function. This object configures the color palette, sets the primary color (you can set anything), and adjusts the theme mode based on the toggleDarkMode state.

 

To keep the theme consistent across the app, we enclose it in the ThemeProvider component. This makes sure all components get the chosen theme throughout the hierarchy.

 

To ensure a uniform appearance across different browsers, we include the CSSBaseline component.

 

In the end, key components such as the NavBar, MyComponent, and Footer are displayed inside the ThemeProvider. This lets them change their look automatically depending on the chosen theme.

 

Step 5: Test your code

 

Test your code by running it with npm start to view your UI in the browser and ensure everything works smoothly. 

 

React Theme Changer Mode

 

Great! In this project, we didn't concentrate on making it responsive because our main goal was to understand its functionality thoroughly.

 

 

Conclusion

 

Dark mode is not only popular, but it is also a great option that allows users to navigate our website easily, especially at night time. With this, users can easily read the content of our website without straining their eyes. The biggest advantage of this is that, with the help of this future, the batteries of phones and computers will also be saved. This is why people like it so much. It is very important for today's modern interface so that the user can do anything with concentration.

 

If you have any questions about this article or related to web development, you can ask them in the question box below, and you will get a reply as soon as possible.

Didn't find your answer? Add your question.

Share

Comments (0)

No comments yet. Be the first to comment!

About Author

Username

Poojan Joshi ( poojanjoshi )

Full Stack JavaScript Developer

Joined On 12 Apr 2024

More from Poojan Joshi

Top 60 Eye-Catching Button Designs Users Can’t Wait to Click - With Source Code

ui-ux

11 Oct 2024

Discover 60 eye-catching button designs with source code, crafted with HTML and CSS to enh....

How to Check Website Speed: Key Metrics, Tools, and Optimization Tips

web-development

21 Sep 2024

Learn how to test your website speed, key metrics to track, top tools to use, and expert o....

Everything About Debouncing Function in JavaScript: Comprehensive Guide

javascript

13 Aug 2024

Learn everything about the debouncing function such as what it is, why and where to use it....

How to Create Advanced Search Bar with Suggestions in React: A Step-by-Step Guide

react-js

2 Aug 2024

Learn to build an advanced React search bar with suggestions, highlighted text, efficient ....

How to Create a Full-Featured Todo List App Using ReactJS

react-js

19 Jul 2024

Learn how to build a powerful Todo List App using ReactJS. A step-by-step guide covering d....

How to Create a Full-Featured Todo List App Using HTML, CSS, and JavaScript

javascript

16 Jul 2024

Learn to build a feature-rich to-do list with HTML, CSS, and JavaScript. Perfect for inter....

Popular Posts from Code Mafias

10 Fun Websites for Stress Relief and Relaxation During Coding Breaks

programming

11 Nov 2024

Top 10 fun websites for coders to relax during breaks. Recharge with interactive games, ar....

Mastering HTML: Top 12 Unique HTML Tags with Examples

html

4 May 2024

Through this article, learn those essential HTML tags that many developers do not know abo....

Top 60 Eye-Catching Button Designs Users Can’t Wait to Click - With Source Code

ui-ux

11 Oct 2024

Discover 60 eye-catching button designs with source code, crafted with HTML and CSS to enh....

How to Upload Code to GitHub: Quick Steps and Detailed Instructions for Beginners

github

16 Sep 2024

In order to upload (push) your project to GitHub, it involves multiple steps that need to ....

How to install MongoDB on windows in 2024

mongodb

2 May 2024

MongoDB is a Database Management System based on NoSQL (Not Only SQL) and utilizes JSON-li....

How to Implement Undo Functionality for Deleting Items in Your React App

react-js

28 Sep 2024

Learn how to implement undo functionality for deleting items in React. Follow a step-by-st....