Implementing Dark Mode in React JS with Tailwind CSS

React JS Tailwind CSS Web Dev

Want to give your React JS app a sleek dark mode? This guide shows you how to do it using Tailwind CSS. Follow our easy, step-by-step instructions to enhance your app’s user experience


NGNishan Giri
2024-06-01
How to implement Dark Mode in React JS with Tailwind CSS

Dark mode has surged in popularity among web users and developers alike, providing a sleek and modern interface option that is both visually appealing and easier on the eyes, particularly in low-light environments. For web developers working with React and Tailwind CSS, implementing dark mode can enhance the user experience by offering a customizable and energy-efficient display alternative. In this guide, we will explore the steps to integrate dark mode into your React JS application using Tailwind CSS. From setting up your project to creating a functional toggle switch, applying responsive dark mode styles, and ensuring user preferences are saved, this tutorial covers all you need to know. Whether you're looking to modernize your existing application or build a new project, this guide will help you leverage dark mode to create a more engaging and user-friendly web experience.

Table of Contents

Why Dark Mode?

Dark mode offers several benefits:

Setting Up the Project

Creating a New React Project

First, let's create a new React project using Create React App. Open your terminal and run:

npx create-react-app dark-mode-app
cd dark-mode-app

Create React App is a convenient way to set up a new React project with all the necessary configurations and dependencies.

Installing Tailwind CSS

Next, we need to install Tailwind CSS. Follow these steps to set it up in your React project:

  1. Install Tailwind CSS via npm:
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

This command installs Tailwind CSS along with its dependencies and initializes the configuration files.

  1. Configure Tailwind CSS: In tailwind.config.js, enable dark mode by setting it to 'class':
module.exports = {
  darkMode: "class", // Enable dark mode via class strategy
  content: ["./src/**/*.{js,jsx,ts,tsx}"],
  theme: {
    extend: {},
  },
  plugins: [],
};

This configuration allows you to apply dark mode styles conditionally using a CSS class.

  1. Add Tailwind to CSS: In src/index.css, add the following lines:
@tailwind base;
@tailwind components;
@tailwind utilities;

These lines import Tailwind CSS’s base, components, and utilities styles into your project.

Implementing Dark Mode

Creating the Toggle Switch

We'll create a toggle switch to enable users to switch between light and dark modes.

  1. Create a Toggle Component: Create a new file src/components/ThemeToggle.js:
import React, { useState, useEffect } from "react";
 
const ThemeToggle = () => {
  const [theme, setTheme] = useState("light");
 
  useEffect(() => {
    if (
      localStorage.getItem("theme") === "dark" ||
      (!("theme" in localStorage) &&
        window.matchMedia("(prefers-color-scheme: dark)").matches)
    ) {
      document.documentElement.classList.add("dark");
      setTheme("dark");
    } else {
      document.documentElement.classList.remove("dark");
      setTheme("light");
    }
  }, []);
 
  const toggleTheme = () => {
    if (theme === "dark") {
      document.documentElement.classList.remove("dark");
      localStorage.setItem("theme", "light");
      setTheme("light");
    } else {
      document.documentElement.classList.add("dark");
      localStorage.setItem("theme", "dark");
      setTheme("dark");
    }
  };
 
  return (
    <button
      onClick={toggleTheme}
      className="bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200 px-4 py-2 rounded"
    >
      {theme === "dark" ? "Switch to Light Mode" : "Switch to Dark Mode"}
    </button>
  );
};
 
export default ThemeToggle;

This component uses useState and useEffect hooks to manage and persist the theme state.

Applying Dark Mode Styles with Tailwind CSS

Now, let's apply dark mode styles using Tailwind CSS.

  1. Modify App Component: In src/App.js, import and use the ThemeToggle component:
import React from "react";
import ThemeToggle from "./components/ThemeToggle";
 
function App() {
  return (
    <div className="min-h-screen bg-white dark:bg-gray-900 text-black dark:text-white">
      <header className="p-4">
        <h1 className="text-2xl">Dark Mode in React with Tailwind CSS</h1>
        <ThemeToggle />
      </header>
      <main className="p-4">
        <p>Welcome to the dark mode demo.</p>
      </main>
    </div>
  );
}
 
export default App;

Here, we use Tailwind CSS classes to apply different styles for light and dark modes.

  1. Style the App: Use Tailwind CSS classes to style the app and ensure that dark mode styles are applied:
/* In src/index.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
 
/* Custom styles if necessary */

This ensures that your styles are correctly applied and that the dark mode styles are activated when the dark mode class is added.

Persisting User Preferences

Ensure that the user's dark mode preference is saved and applied on subsequent visits.

  1. Update ThemeToggle Component: The component already includes logic to save and load the theme preference using localStorage.

Best Practices for Dark Mode Design

Conclusion

Implementing dark mode in your React JS project using Tailwind CSS is straightforward and enhances user experience. By following this guide, you can create a visually appealing and functional dark mode feature for your web applications. Dark mode not only modernizes the look of your application but also caters to user preferences and accessibility needs.

Additional Resources

By implementing these steps, you ensure that your application is up-to-date with current web development trends and provides a better user experience. If you have any questions or need further assistance, feel free to leave a comment below.

FAQs

How do I enable dark mode in React JS using Tailwind CSS?

To enable dark mode in React JS using Tailwind CSS, you need to set the darkMode option to 'class' in the tailwind.config.js file. Then, create a toggle component to switch between light and dark modes by adding or removing the 'dark' class to the root element.

Can I use Tailwind CSS to apply dark mode styles conditionally?

Yes, Tailwind CSS allows you to apply dark mode styles conditionally by using the dark: prefix. For example, dark:bg-gray-900 will apply the bg-gray-900 class when dark mode is enabled.

How can I save user preferences for dark mode in a React JS application?

You can save user preferences for dark mode using the localStorage

What are some best practices for designing a dark mode interface?

Best practices for designing a dark mode interface include ensuring sufficient color contrast, using the consistent icon

Happy Coding! 😊