How to Add Dark Mode in ReactJS using Tailwind CSS?


Dark mode has become one of the important aesthetic additions that one might think in recent years. It offers several benefits like reduced eye strain, improved accessibility, and a modern aesthetic. And this might be tempting enough for you to add this functionality to your web pages. And this might even be way easier than you might actually think. By combining two of the most widely used frameworks ReactJS and Tailwind CSS, you can add dark mode to your web pages quickly and easily.

useState() Hook

useState is a hook in React that allows you to add state to your functional components. State is an object that holds data that can change over time, and it's used to store and manage component data that affects its behavior or render.

Syntax

const [state, setState] = useState(initialValue);

Here's what each part of the syntax does −

  • useState − The hook that you call to add state to your component.

  • stateVariable − The name of the state variable that you want to create. This is the first value in the returned array from useState.

  • setStateVariable − The function that you use to update the state. This is the second value in the returned array from useState.

  • initialValue − The initial value for the state. This is the argument that you pass to useState when you call the hook. The initial value is used to initialize the state the first time the component is rendered.

useState returns an array with two values: the current state value, and a function to update it.

useEffect() Hook

useEffect is a hook in React that lets you synchronize a component with an external system, such as a back-end API, a timer, or a mouse event handler. It helps you manage side effects, which are functions that can modify or update the state or other parts of the application when a component is mounted, updated, or unmounted.

Syntax

useEffect(() => {
   // Your code here
   return () => {
      // Clean up code here (optional)
   };
}, [dependency1, dependency2, ...]);

useEffect takes two arguments −

  • A callback function that will run whenever a component is updated.

  • A list of dependencies that tell useEffect when to run the callback.

Approach

We will use a custom component to add that will be responsible for toggling between dark and light mode. In this component, we will make use of the above mentioned useState() hook to keep track of the current mode (light or dark) and useEffect() hook to update the document's body class when the mode changes. We will use Tailwind CSS to provide styling to the different components in all the modes.

Example

The following example’s implementation is divided into several files: index.js, index.css, App.js, DarkModeToggle.js, and dark-mode.css. In index.js, React, ReactDOM, and two CSS files are imported. App.js sets up the app's structure with a dark mode toggle and content. DarkModeToggle.js returns a button with bg-gray-500 class for the background and other classes for text and border properties. dark-mode.css defines the appearance of the dark mode, including background and text colors. The darkMode state is toggled with useState hook and changes the class name of the main container to light or dark. This implementation demonstrates using Tailwind CSS to easily add dark mode to ReactJS.

Step 1 − We will start by conceiving the React application.

npx create-react-app dark-mode

Step 2 − We will now switch to the application directory.

cd dark-mode

Step 3 − Let us now install Tailwind CSS.

npm install tailwindcss

The following is the complete code of all the files in the src folder which were modified in this example −

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import './dark-mode.css';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));

index.css

@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
body {
   margin: 0;
   font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
   'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
   sans-serif;
   -webkit-font-smoothing: antialiased;
   -moz-osx-font-smoothing: grayscale;
}
code {
   font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
   monospace;
}

App.js

import React, { useState } from 'react';
import DarkModeToggle from './DarkModeToggle';
function App() {
   const [darkMode, setDarkMode] = useState(false);
   return (
      <div className={`${darkMode ? 'dark' : 'light'} mode-container`}>
         <div style={{margin: "10px"}}>
            <DarkModeToggle darkMode={darkMode} setDarkMode={setDarkMode}/>
            h1>How to Add Dark Mode in ReactJS using Tailwind CSS?</h1>
            <br/>
            <br/>
            <p>This is some text.</p>
            <br/>
            <p>This is some more text.</p>
         </div>
      </div>
   );
}
export default App;

DarkModeToggle.js

import React from 'react';
function DarkModeToggle({ darkMode, setDarkMode }) {
   return (
      <button
         className={`bg-gray-500 hover:bg-gray-700 text-white font-medium py-2 px-4 rounded-md ${darkMode ? 'active' : ''}`}
         onClick={() => setDarkMode(!darkMode)}
         >
         {darkMode ? 'Light Mode' : 'Dark Mode'}
      </button>
   );
}
export default DarkModeToggle;

dark-mode.css

.mode-container {
   background-color: #f5f5f5;
   position: fixed;
   top: 0;
   left: 0;
   bottom: 0;
   right: 0;
   overflow: auto;
}
.dark {
   background-color: #222222;
   color: #f5f5f5;
}
.light {
   background-color: #f5f5f5;
   color: #222222;
}

Output

File output dark mode.gif is going to be inserted here

Conclusion

To culminate, the integration of a gloomy mode aspect in your ReactJS application exploiting Tailwind CSS can amplify the user experience and deliver a more convenient survey encounter for those preferring dim-light surroundings. The procedural guide presented in this write-up facilitates the implementation of this feature with nominal modifications to the code. The vast repertoire of advanced tools and libraries accessible in the ReactJS ecosystem empowers developers to build alluring and immersive applications that are adaptable to a range of user inclinations. Thus, the integration of this oft-overlooked attribute in your web application portrays your commitment to provide a holistic and exclusive user experience, ultimately enabling you to differentiate from the rivals.

Updated on: 10-Apr-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements