How to Enable Dark Mode in ReactJs

Table of contents

No heading

No headings in the article.

Enabling dark mode in a ReactJS application can be done using various methods. Here are some ways to achieve this:

  1. Using CSS variables:

One of the simplest ways to implement dark mode in a ReactJS application is by using CSS variables. You can define CSS variables for colors and toggle between light and dark modes by changing the values of these variables.

Using CSS variables, enabling mode becomes easy. We can achieve it via conditional statements: when the color is white and the background color is black, it is in the dark mode state. Now our task is to enable light mode.We can acheive it by inverting the CSS properties and changing the text of the button.This is how, using state, we can easily change the mode.

Here's an example of how to use CSS variables to enable dark mode in ReactJS:

import React, { useState } from "react";

function About() {
  const [myStyle, setMyStyle] = useState({
    color: "black",
    backgroundColor: "white",
  });

  const [btntext, setBtntext] = useState("Enable Dark Mode");

  const toggleStyle = () => {
    if (myStyle.color == "black") {
      setMyStyle({
        color: "white",
        backgroundColor: "black",
        border: '1px solid white',
      });
      setBtntext("Enable Light Mode");
    } else {
      setMyStyle({
        color: "black",
        backgroundColor: "white",
      });
      setBtntext("Enable Dark Mode");
    }
  };

  return (
          <div className="container">
            <button onClick={toggleStyle} className="btn btn-primary my-3">{btntext}</button>
          </div>
  );
}

export default About;
  1. Using a third-party library:

There are many third-party libraries available that can be used to implement dark mode in a ReactJS application, such as React Dark Mode, React Toggle Dark Mode, and Dark Mode Toggle. These libraries provide pre-built components and functionalities that can be easily integrated into your application.

  1. Using window.matchMedia():

Another way to implement dark mode is by using the window.matchMedia() method to detect whether the user prefers dark mode or light mode, and updating the application accordingly.