DEV Community

loading...
Cover image for 【Step by Step】How to implement Dark Mode with Tailwind CSS on React

【Step by Step】How to implement Dark Mode with Tailwind CSS on React

taishi profile image Taishi Originally published at en.taishikato.com Updated on ・4 min read

This article is also on Medium and en.taishikato.com

Taishi here👋

Today I am going to write about how to implement Dark Mode with Tailwind CSS.
Dark Mode is now one of the important features for usability and you should implement this on your website if you have not done yet.

Don't worry. It's quite easy!

BTW, the complete example on GitHub is here ✌️

GitHub logo taishikato / Dark-Mode-with-Tailwind-CSS

This repo is for my article: https://dev.to/taishi/step-by-step-how-to-implement-dark-mode-with-tailwind-css-on-react-3565

Create your React app with CRA CLI

$ npx create-react-app dark
Enter fullscreen mode Exit fullscreen mode

Let's host it on http://local:3000

$ cd dark
$ npm run start
Enter fullscreen mode Exit fullscreen mode

Now I believe you see this page on your http://localhost:3000 🎉

React default page

This time we don't need ./src/App.css, so delete the file and make ./src/App.js simpler like below😸

import React from 'react';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Now the website looks much simpler.

simple react page

Add Tailwind CSS

Let's add packages for Tailwind CSS

$ npm i tailwindcss autoprefixer postcss-cli --save-dev
Enter fullscreen mode Exit fullscreen mode

Generate a config file of Tailwind CSS.

The command below creates ./tailwind.config.js.

$ npx tailwindcss init
Enter fullscreen mode Exit fullscreen mode

Add postcss.config.js

The content looks like this.

module.exports = {
  plugins: [
    require('tailwindcss'),
    require('autoprefixer'),
  ],
};
Enter fullscreen mode Exit fullscreen mode

Make a Stylesheet file.

Let's add a ./src/tailwind.src.css like below.

@tailwind base;

@tailwind components;

@tailwind utilities;
Enter fullscreen mode Exit fullscreen mode

Add a script to generate a CSS file

tailwind:css on package.json builds a CSS file as ./src/tailwind.css you actually use in your React app.

"scripts": {
+   "tailwind:css": "tailwind build src/tailwind.src.css -c tailwind.config.js -o src/tailwind.css",
     "start": "react-scripts start",
     "build": "react-scripts build",
     .
     .
     .
Enter fullscreen mode Exit fullscreen mode

Let start and build use tailwind:css.

"scripts": {
  - "start": "react-scripts start",
  - "build": "react-scripts build",
  + "tailwind:css": "tailwind build src/tailwind.src.css -c tailwind.config.js -o src/tailwind.css",
  + "start": "npm run tailwind:css && react-scripts start",
  + "build": "npm run tailwind:css && react-scripts build",
Enter fullscreen mode Exit fullscreen mode

Every time you use the start or build script, it generates a CSS file for you👍

Let's import tailwind.css in App.js

import React from 'react';
+ import ./'tailwind.css';

 function App() {
   return (
Enter fullscreen mode Exit fullscreen mode

All set! Now your app uses Tailwind CSS 🌬️

Use Tailwind CSS to align your text

Just try to use a class text-center from Tailwind CSS. Now our App.js looks like below.

import React from 'react';
import './tailwind.css';

function App() {
  return (
    <div className="App">
      <header className="App-header text-center">
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Your web page looks like below.

text center

Customize Tailwind CSS for Dark mode

We want to use dark: like this. In this example, when the value of prefers-color-scheme is dark, bg-black becomes valid.

<div className="dark:bg-black">
Enter fullscreen mode Exit fullscreen mode

First, we need to customize tailwind.config.js to make it happen😎

Customize the screens property

Your current tailwind.config.js should look like this.

module.exports = {
  future: {
    // removeDeprecatedGapUtilities: true,
    // purgeLayersByDefault: true,
  },
  purge: [],
  theme: {
    extend: {},
  },
  variants: {},
  plugins: [],
}
Enter fullscreen mode Exit fullscreen mode

Add screens property under extend.

module.exports = {
  future: {
    removeDeprecatedGapUtilities: true,
    purgeLayersByDefault: true,
  },
  purge: ['./src/App.js'],
  theme: {
    extend: {
      screens: {
        dark: { raw: '(prefers-color-scheme: dark)' },
      },
    },
  },
  variants: {},
  plugins: [],
}
Enter fullscreen mode Exit fullscreen mode

What's gonna happen!?

According to the Tailwind CSS document - Custom media queries, we can make our own screen, which means tailwindcss command generates CSS like this:

@media (prefers-color-scheme: dark) {
  .dark\:container {
    width: 100%;
  }

  @media (min-width: 640px) {
    .dark\:container {
      max-width: 640px;
    }
  }
  .
  .
Enter fullscreen mode Exit fullscreen mode

Let's execute npm run start again to generate a new tailwind.css and check the file 👀

dark tailwind code

It's working!

Dark Mode

Let's make your app dark mode available 😈

Just add dark:bg-black dark:text-white on App.js.

import React from 'react';
import './tailwind.css';

function App() {
  return (
    <div className="App dark:bg-black dark:text-white">
      <header className="App-header text-center">
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Now it has Dark Mode 👽

dark mode is working

Thank you for reading.

Discussion (11)

pic
Editor guide
Collapse
futureistaken profile image
R Z

This is fine, just an extra 2 MB of "CSS" code, extra work for the browser, and just making our components dependent on external CSS. In fact, this list should be longer!

Collapse
thomasledoux1 profile image
Thomas Ledoux

You can easily purge the CSS from Tailwind. They have a whole doc section about it: tailwindcss.com/docs/controlling-f...

Collapse
futureistaken profile image
R Z

This approach has a dark side!

Thread Thread
thomasledoux1 profile image
Collapse
taishi profile image
Taishi Author

Yes, we can easily purge the CSS 😁

Collapse
iamdavidlevai profile image
Dávid Lévai

If you set up PostCSS and purge correctly, there won't be any problems with CSS size. You can easily set up inlining critical CSS too to help speed up loading and Lighthouse scores too.

Collapse
taishi profile image
Taishi Author

Yeeees👍

Collapse
anirudhrowjee profile image
Anirudh Rowjee

Perhaps the most to-the-point tailwind tutorial i've ever seen so far. Great Work!

Collapse
taishi profile image
Taishi Author

Thank you for the kind words 😆

Collapse
fajarsiddiq profile image
Fajar Siddiq

maji yabai 🔥 thanks for sharing Taishi

Collapse
taishi profile image
Taishi Author

Hey, Fajar!

Thank you for the comment!
Maji Yabai🔥