React 18 Tailwind CSS Add Light and Dark Mode Toggler Tutorial

Last Updated on by in React JS

In this guide, we are going to learn how to add dark mode and light mode in React application using Tailwind CSS 3. Not just that, we will also show you how to install and configure TailwindCSS 3 in React js app from absolute scratch.

The dark mode is a popular display setting for making the user interfaces easily viewable. It is generally found in smartphones or laptops.

The primary reason behind dark mode is that it decreases the light radiated by device screens while preserving the minimum color contrast ratios needed for readability.

The dark mode is known as black mode, dark theme, and night mode. It uses light-colored text, icons, and graphical user interface elements on a dark background.

How to Integrate Dark and Light Mode in React js using Tailwind CSS

  • Step 1: Create React App
  • Step 2: Set Up Tailwind in React
  • Step 3: Create Component File
  • Step 4: Set Up Dark Mode in React
  • Step 5: Update App Js File
  • Step 6: Test App in Browser

Create React App

The Create React App tool sets up the environment for React development; here is the command that will install the tool globally in your system.

npm install create-react-app --global

Execute the command to create a new react project.

npx create-react-app react-demo

After the app is formed move into the project folder.

cd react-demo

Set Up Tailwind in React

We have to install tailwindcss using the npm and subsequently execute the tailwind css initializer command.

npm install -D tailwindcss --legacy-peer-deps
npm install @heroicons/react --legacy-peer-deps

npm install @headlessui/react --legacy-peer-deps
npx tailwindcss init

The tailwind CSS init command created the tailwind.config.js file; you need to update the content property with the given values.

module.exports = {
  darkMode: 'class',
  content: ['./src/**/*.{html,js}'],
  theme: {
    extend: {},
  },
  plugins: [],
}

In order to work the Dark toggle button, make sure to set class property to darkMode property in the tailwind configuration file.

Next, open App.css file and add the @tailwind directives for each of Tailwind’s layers to your main CSS file.

@tailwind base;
@tailwind components;
@tailwind utilities;

Next, execute the command to run the CLI tool to scan React template files for classes and build your CSS.

npx tailwindcss -i ./src/App.css -o ./src/styles/output.css --watch

Create Component File

In the src/ folder, create a brand new folder named /components, in here create create the Home.js file.

Put the following code into the file.

import React from 'react'

function Home() {
  return (
    <div>Home</div>
  )
}

export default Home

Set Up Dark Mode in React

Get into the components/Home.js file, and insert the entire given code.

We are using a pretty basic Tailwind Card component; we will set the initial state with a boolean value false. That means initially; the card will have a light theme; by using the useState hook, we will toggle the dark mode in the Tailwind React card.

import React from 'react'

function Home() {
  const [darkToggle, setDarkToggle] = React.useState(false)

  return (
    <div
      class={`h-screen w-full flex items-center justify-center bg-gray-300 flex-col ${
        darkToggle && 'dark'
      }`}
    >
      <label class="toggleDarkBtn">
        <input type="checkbox" onClick={() => setDarkToggle(!darkToggle)} />
        <span class="slideBtnTg round"></span>
      </label>

      <div class="max-w-sm rounded overflow-hidden bg-gray-100 p-5 rounded-lg mt-4 text-white dark:bg-gray-900">
        <img
          class="w-full"
          src="https://v1.tailwindcss.com/img/card-top.jpg"
          alt="Sunset in the mountains"
        />
        <div class="px-6 py-4">
          <div class="text-gray-800 dark:text-gray-200 font-bold text-xl mb-2">
            The Coldest Sunset
          </div>
          <p class="text-gray-800 dark:text-gray-200">
            Lorem ipsum dolor sit amet, consectetur adipisicing elit.
            Voluptatibus quia, nulla! Maiores et perferendis eaque,
            exercitationem praesentium nihil.
          </p>
        </div>
        <div class="px-6 pt-4 pb-2">
          <span class="inline-block bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700 mr-2 mb-2">
            #photography
          </span>
          <span class="inline-block bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700 mr-2 mb-2">
            #travel
          </span>
          <span class="inline-block bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700 mr-2 mb-2">
            #winter
          </span>
        </div>
      </div>
    </div>
  )
}

export default Home

We will have to open the index.css file, then at the first line import the output.css and define the custom css to style the dark theme toggle button.

@import url("./styles/output.css");

.toggleDarkBtn {
  position: relative;
  display: inline-block;
  width: 65px;
  height: 41px;
}

.toggleDarkBtn input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slideBtnTg {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgb(241, 40, 40);
  -webkit-transition: 0.5s;
  transition: 0.5s;
}

.slideBtnTg:before {
  position: absolute;
  content: "";
  height: 30px;
  width: 30px;
  left: 5px;
  bottom: 5px;
  -webkit-transition: 0.5s;
  transition: 0.5s;
  background-color: white;
}

input:checked + .slideBtnTg {
  background-color: #1d1e1f;
}

input:focus + .slideBtnTg {
  box-shadow: 0 0 1px #2196f3;
}

input:checked + .slideBtnTg:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

.slideBtnTg.round {
  border-radius: 34px;
}

.slideBtnTg.round:before {
  border-radius: 50%;
}

Update App Js File

Open the App.js file, then you have to import the Home component in the main app component file.

import './App.css'
import Home from './components/Home'

function App() {
  return (
    <div className="App">
      <Home />
    </div>
  )
}

export default App

Test App in Browser

Let’s run the command to start the react server:

npm start

You can open the app and click on toggle button to switch between light and dark theme in React.

http://localhost:3000

React Js Tailwind CSS Add Light and Dark Mode Toggler Tutorial

Conclusion

In this React Dark mode tutorial, we have learned how to set up tailwind UI in React, and how to integrate and configure dark mode in the Tailwind UI component within the React environment.