Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

How to Improve User Experience With Tailwind Dark Mode

The incorporation of dark mode in web and mobile applications has become a crucial aspect of software development. Dark mode (dimmed mode), a user interface that employs a dark color scheme, is more than just a design trend. It is a feature that offers substantial benefits, including health-related ones. It minimizes the emission of blue light, which can disrupt sleep patterns and overall health, as per the Sleep Foundation. This is particularly relevant as screen time continues to increase. Additionally, the dimmed mode can prolong battery life, especially on OLED (Organic Light-Emitting Diode) screen devices, by up to 33%.

From a design perspective, dimmed mode introduces new opportunities for creativity. It provides superior contrast and readability, making it gentler on the eyes and improving the overall user experience. Therefore, it’s essential to consider incorporating dimmed mode in your web or mobile apps during the software development process.

Implementing Dark Mode with Tailwind CSS

Before delving into the dark world 😎, at Purecode.ai, we are revolutionizing the development process of software by eliminating the challenging aspect of building your components from scratch. Explore our repository of 10, 000+ AI-generated Tailwind CSS components to speed up your web app development.

In this article, I will walk you through setting up dark mode in your React application.

Integrating Tailwind CSS in Your React App

To kick start the process of integrating dark version of your React application with Tailwind, we first need to set up Tailwind in our project. Follow these steps to achieve this:

Prerequisites

Before proceeding, ensure you have the following:

  • NPM is installed on your machine.

  • Basic knowledge of JavaScript and React.

If you need help getting started with React, check out the video tutorial below.

Setting up a React App

In your terminal, enter the following command to create a new React application:

npx create-react-app my-app && cd my-app

Once your app is set up, run the application by entering either of these commands in your terminal:

yarn start

Or using npm:

npm start

Your server should launch in your browser at http://localhost:3000/, as shown below:

React app

Installing Tailwind CSS in Your App

Firstly, add Tailwind CSS to your project’s dependencies. To accomplish this, launch your terminal and execute the following command:

npm install tailwindcss

This will install Tailwind CSS as a dependency on your React application

Implementing Tailwind CSS Dark Mode in Your React Application

Now that we have Tailwind CSS installed, we can proceed to implement dark mode in our React application. There are three primary methods to achieve this:

  1. Enabling Dark Mode in the tailwind.config.js File: This method involves configuring Tailwind to automatically apply dark mode styles based on a user’s preferred color scheme.

  2. The Class-Based Approach: This method involves manually toggling between light and dark modes based on a specific class in your HTML document.

  3. Using a Custom Hook (useDarkMode.js): This method involves creating a custom React hook that manages the theme state and persists the user’s theme preference in the local storage.

In the following sections, we will explore each of these methods in detail.

Creating a tailwind.config.js File in the Root of Your Project

Start by initializing Tailwind by running this command on your terminal:

npx tailwindcss init

This command generates a Tailwind configuration file. This file can be customized to include paths to all your template files, including those related to dark mode settings.

module.exports = {
  darkMode: 'class',
  content: ['./src/**/*.{js,jsx,ts,tsx}'],
  theme: {
    extend: {},
  },
  plugins: [],
  purge: [
    "./src/**/*.{js,jsx,ts,tsx}"
  ],
};

In this configuration file, we outline the settings for Tailwind CSS. The purge option is set to scan specific files, all (.jsx, .tsx, .js, .ts) files for utilized classes, optimizing the final output. We also set darkMode to class, which activates the dark mode by default.

We could also disable it by passing false instead of an array.

module.exports = {
  darkMode: 'class',
  content: ['./src/**/*.{js,jsx,ts,tsx}'],
  theme: {
    extend: {},
  },
  plugins: [],
  purge: false
};

This is helpful if we are purging them using another tool.

Importing Tailwind CSS in your index.css file

@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';

In this segment of the code, we are importing the base styles, component classes, and utility classes from Tailwind into our index.css file.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

ReactDOM.render(
<React.StrictMode>
    <App />
</React.StrictMode>,
document.getElementById('root')
);

This concludes the setup of Tailwind within our React project.

Next, we will focus on integrating a dark mode feature. Given that Tailwind CSS is now properly configured, we can proceed with the implementation of dark mode in our React application. The code example below ⬇ demonstrates this:

Enabling Tailwind CSS Dark Mode in the tailwind.config.js File

// tailwind.config.js

module.exports = {
  purge: ['./src/**/*.{js,jsx,ts,tsx}', './public/index.html'],
  darkMode: 'class', // or 'media' or 'false'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
  purge: [
    "./src/**/*.{js,jsx,ts,tsx}"
  ],
};

  • In this configuration, the darkMode property is assigned the value class. This signifies that the dark mode is activated by appending the dark class to the HTML element. Consequently, we can leverage this class to apply distinct styles when the dark mode is turned on.

  • If we assign the darkMode property the value of media, the theme will be set based on the operating system.

  • If we assign the darkMode property the value of false, then the dark mode will be disabled.

Class-Based Approach: Leveraging CSS Classes for Theme Switching

Here, we manually toggle between light and dark modes using CSS classes. By default dark mode uses the prefers-color-scheme CSS media feature, but you can also build sites that support toggling dark mode manually using the “class” strategy.

Dark mode is a first-class feature of many operating systems, it has become more common to design a dark version of your website to go along with the default design. Tailwind CSS has a dark variant that lets you style your site differently when dark mode is enabled. This method offers a high degree of control and flexibility, making it a popular choice among developers.

  • First, we set the darkMode property to “class” in the tailwind.config.js file. This configuration instructs Tailwind to activate dark mode when the “dark” class is present in the HTML tag.

  • Next, we include a “dark” class in our HTML tag. This action triggers the class-based dimmed mode, allowing us to apply distinct styles when the dark mode is active. The code below demonstrates this approach ⬇

<html lang="en" class="dark"></html>

To implement a dark mode, we can add the dark: prefix to the class names that we want to modify. For example, if we want the background color of our page to be darker, we can choose a dark color like bg-gray-900 and prefix it with dark: This will make the background color of the page gray when the dark mode is active. We can also add the text color to be white when the dark mode is active by adding the class “dark:text-white“.

<div class="bg-white dark:bg-gray-900 text-black dark:text-white"></div>

Granular Control with the “dark:” Prefix: Fine-Tuning Dark Mode Styles

Tailwind introduces the “dark:” prefix, a powerful tool that provides granular control over styles in dark mode. This prefix can be used to modify a wide range of styles, including but not limited to colors, text sizes, and margins. By using the “dark:” prefix, developers can fine-tune the appearance of their application in dark mode, ensuring an optimal user experience.

Building Our React App with Dark Mode Feature using Custom Hook

To demonstrate the functionality of the dark mode, we will build an “About Us” component and add a toggle interface to switch between the light and dark themes.

Before building the “About Us” component, we will first develop a custom hook. Create a new directory, and within this directory, create a file named useDarkMode.js

Within your useDarkMode.js file, input the subsequent code:

// src/hooks/useDarkMode.js

import { useEffect, useState } from 'react';

export default function useDarkMode() {
  const [theme, setTheme] = useState(localStorage.theme);
  const colorTheme = theme === 'dark' ? 'light' : 'dark';

  useEffect(() => {
    const root = window.document.documentElement;
    root.classList.remove(colorTheme);
    root.classList.add(theme);

    // save theme to local storage
    localStorage.setItem('theme', theme) // if NOT set via local storage previously;
  }, [theme, colorTheme]);

  return [colorTheme, setTheme];
}

Our custom hook, useDarkMode, uses the useState and useEffect hooks from React.

Initially, the useState hook sets the theme state to the value stored in localStorage.theme. The localStorage object is a web storage API that allows us to persist data in the user’s browser, even after a page refresh or browser closure.

We then define a variable colorTheme that is dependent on the theme state. If the theme is “dark”, colorTheme will be “light”, and vice versa. This mechanism enables the toggling between two contrasting themes.

The useEffect hook is employed to dynamically update the HTML document’s theme based on the theme and colorTheme states and to persist the theme in the localStorage.

The useEffect hook accepts two parameters: a callback function and an array of dependencies. In this context, the dependencies array is [theme, colorTheme], implying that the callback function within the useEffect hook will be invoked whenever the theme or colorTheme changes.

Within the useEffect function, we manipulate the classList property to add or remove a class from the root element of the HTML document (window.document.documentElement). This manipulation enables the application of theme-specific styles to the document.

In conclusion, the useDarkMode hook returns an array comprising the current colorTheme and the setTheme function, which can be utilized to modify the theme state. This design pattern allows other components to interact with and modify the theme state without the need for redundant code.

Building the Switcher UI Component

In the src directory, create a new file named Switcher.js and populate it with the subsequent code.

// src/components/Switcher.js

import React, { useState } from 'react';
import useDarkMode from './hooks/useDarkMode';
import { DarkModeSwitch } from 'react-toggle-dark-mode';

export default function Switcher() {
  const [colorTheme, setTheme] = useDarkMode();
  const [darkSide, setDarkSide] = useState(colorTheme === 'light' ? true : false);

  const toggleDarkMode = checked => {
    setTheme(colorTheme);
    setDarkSide(checked);
  };

  return (
    <>
      <div>
        <DarkModeSwitch checked={darkSide} onChange={toggleDarkMode} size={48} />
      </div>
    </>
  );
}

The preceding code snippet incorporates two custom hooks: useDarkMode and DarkModeSwitch, in addition to the useState hook from the React library.

The useDarkMode hook yields the current color theme and a function to modify it.

DarkModeSwitch is a toggle switch component from the react-toggle-dark-mode library. It accepts three properties:

  • checked: a boolean value that signifies whether the switch is activated or deactivated. It is initialized to the value of the darkSide state.

  • onChange: a function that is invoked whenever the switch is toggled. It is set to toggleDarkMode.

  • size: an optional numeric value that determines the size of the switch. In this instance, it is set to 48.

The useState hook is utilized to initialize the darkSide state, which is set to true if the current colorTheme is light, and false otherwise.

The toggleDarkMode function is invoked whenever the DarkModeSwitch is toggled. It updates the colorTheme using the setTheme function from the useDarkMode hook and sets the darkSide state to the new value of the switch.

In conclusion, the Switcher component returns the DarkModeSwitch component encapsulated in a div element and is rendered as the default export of the module.

Building Our “About Us” Component

Create a file named “AboutUs.js” under the components folder and then paste the following code:

// src/components/AboutUs.js

import React from "react";

function AboutUs() {
  return (
    <div className="w-full md:w-1/2 lg:w-2/6">
      <div className="bg-white dark:bg-gray-800 m-4 rounded-lg shadow-2xl">
        <img
          src="<https://helene-ui.netlify.app/ui/overlay-chat-ui/img/embedded-image.png>"
          alt="Post"
          className="rounded-t-lg"
        />
        <div className="px-4 pt-2">
          <h1 className="font-bold mt-2 text-2xl text-gray-800 dark:text-gray-300">
            Who We Are?
          </h1>
          <h3 className="text-gray-500 dark:text-gray-300">
            {" "}
            We are an Incredible Team
          </h3>
          <p className="text-gray-400 dark:text-gray-400 my-4">
            We are a diverse group of passionate individuals who come together
            with a shared vision and unwavering dedication to making a
            difference. Our team embodies excellence and innovation
          </p>
        </div>
        <div className="px-4 pb-2">
          <a
            href="<https://pbs.twimg.com/profile_images/1574491799841914906/-6LkU4gy_400x400.jpg>"
            target="_blank"
            rel="nonreferrer"
            className="flex items-center"
          >
            <img
              src="<https://pbs.twimg.com/profile_images/1574491799841914906/-6LkU4gy_400x400.jpg>"
              width="32"
              alt="Avatar"
              className="rounded-full"
            />
            <div className="ml-2">
              <p className="text-gray-500 dark:text-gray-300 text-sm">
                <a href="<https://twitter.com/eunit99>">@eunit99</a>
              </p>
            </div>
          </a>
        </div>
        <div className="p-4">
          <span className="inline-block bg-gray-300 dark:bg-gray-500 rounded-full px-3 py-1 text-xs font-semibold text-gray-500 dark:text-gray-300 mr-2 mb-2">
            #react
          </span>
          <span className="inline-block bg-gray-300 dark:bg-gray-500 rounded-full px-3 py-1 text-xs font-semibold text-gray-500 dark:text-gray-300 mr-2 mb-2">
            #Tailwind
          </span>
          <span className="inline-block bg-gray-300 dark:bg-gray-500 rounded-full px-3 py-1 text-xs font-semibold text-gray-500 dark:text-gray-300 mr-2 mb-2">
            #darkmode
          </span>
        </div>
      </div>
    </div>
  );
}

export default AboutUs;

About Us component

The “About Us” component, defined in this code, is a React component that displays an About Us containing a title, description, image, and a few tags. This about us serves as a practical example of how to implement a dark and light mode in a React application using Tailwind.

import About us from './AboutUs';
import Switcher from './Switcher';

function App() {
  return (
    <div className="min-h-screen flex flex-col items-center transition duration-200 dark:bg-gray-900 p-10">
      <Switcher />
      <AboutUs />
    </div>
  );
}

export default App;

This React application incorporates two components: an About Us and a Switcher. The “About Us” component is responsible for rendering an about us that contains specific information, whereas the Switcher component facilitates the switching between dark and light themes within the application.

The App component functions as the application’s root component, which renders both the About Us and Switcher components. It also adjusts the background color and other stylistic elements based on the current theme (either dark or light).

Implementing the App Component

Next, we will proceed to instantiate the App component within the index.js file.

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

The complete code for this application can be found in this CodeSandbox.

Next Steps

In this article, you learned about the benefits of dimmed mode in software development, and how dark mode aligns with the growing consumer preference for dark backgrounds with colored text. Tech giants have already adopted this trend, and it’s clear that users appreciate having the option to switch to dark mode.

You learned how to enable dark mode and light mode in your React applications using Tailwind.

We identified three steps to doing this:

  • Enabling dark mode in the tailwind.config.js File,

  • the Class-Based Approach by adding a dark class on your HTML element,

  • and using a custom hook, where we used the useDarkMode.js.

Further Readings

In any case, PureCode’s AI can help you with save time building robust web applications. Choose from over 10,000 AI-generated custom components that are production-ready.

Happy building 💻

Emmanuel Uchenna

Emmanuel Uchenna

Emmanuel is an experienced and enthusiastic software developer and technical writer with 4+ proven years of professional experience. He focuses on full-stack web development. He is fluent in React, TypeScript, VueJS, and NodeJS and familiar with industry-standard technologies such as version control, headless CMS, and JAMstack. He is passionate about knowledge sharing.