DEV Community

Darren White
Darren White

Posted on • Updated on • Originally published at darrenwhite.dev

Tailwind CSS and useDarkMode hook

Background

I've been using tailwindcss for a couple of years now. Version 2 includes the option to easily add dark mode. I thought I'd give it a try on my blog which is built using Next.js

Setup

To begin I'll assume you have a react based website with tailwindcss already set up. In the tailwind.config.js file add a darkMode option:

// tailwind.config.js
module.exports = {
  darkMode: 'class', // can also be set to 'media'
  // ...
}
Enter fullscreen mode Exit fullscreen mode

Now when adding your styles add a dark variant alongside the 'light' styles:

<div class="bg-white dark:bg-gray-800">
  <h1 class="text-gray-900 dark:text-white">Dark mode is here!</h1>
  <p class="text-gray-600 dark:text-gray-300">
    Lorem ipsum...
  </p>
</div>
Enter fullscreen mode Exit fullscreen mode

If the .dark class is present earlier in the html tree then the dark theme will be applied.

useDarkMode Hook

For activiating the .dark class, I'm using the excellent useDarkMode hook by Donavon West which you'll need to install:

npm i use-dark-mode
Enter fullscreen mode Exit fullscreen mode

The plugin works by toggling a class added to the body element (or a different element if specified):

body.light-mode {
  background-color: #fff;
  color: #333;
  transition: background-color 0.3s ease;
}
body.dark-mode {
  background-color: #1a1919;
  color: #999;
}
Enter fullscreen mode Exit fullscreen mode

However, as mentioned previously tailwindcss applies the dark mode if there is a .dark class, therefore, the default classes will need to be overridden by passing the options to the useDarkMode hook:

const { toggle, value } = useDarkMode(initialState, {
    classNameDark: 'dark',
    classNameLight: 'light',
  });
Enter fullscreen mode Exit fullscreen mode

And thats it unless you are using the tailwindcss typography plugin.

tailwindcss typgraphy

As my blog content is taken Markdown files I'm using the tailwindcss typography plugin to add typograhic styles to my content. This is done by adding a .prose class to the content wrapper element:

<article class="prose">
  {{ markdown }}
</article>
Enter fullscreen mode Exit fullscreen mode

For the dark theme:

<article class="prose prose-dark">
  {{ markdown }}
</article>
Enter fullscreen mode Exit fullscreen mode

For the blog content I would check the value returned and apply the classes accordingly:

const BlogDetails = () => {
  const { darkMode } = useTheme();

  return (
    <AppShell>
      <NextSeo title={`${title} | dlw`} description={snippet} />
      <Container>
        <MDXProvider components={mdxComponents}>
          <article className={`${darkMode ? 'prose prose-dark' : 'prose'}`}>{children}</article>
        </MDXProvider>
      </Container>
    </AppShell>
  );
};

export default BlogDetails;
Enter fullscreen mode Exit fullscreen mode

The issue I ran into was the .dark class would be applied by the hook but the value available when setting the .prose value could be out of sync resulting in unreadable text:

tailwindcss-dark-mode-issue

My solution was to wrap the useDarkMode hook in my own custom hook:

import { useEffect } from 'react';
import useDarkMode from 'use-dark-mode';

export const useTheme = (initialState = false) => {
  const { toggle, value } = useDarkMode(initialState, {
    classNameDark: 'dark',
    classNameLight: 'light',
  });

  useEffect(() => {
    const proseEl = document.querySelector('article.prose');

    if (!proseEl) {
      return;
    }

    if (value) {
      document?.querySelector('article.prose').classList.add('prose-dark');
    } else {
      document?.querySelector('article.prose').classList.remove('prose-dark');
    }
  }, [value]);

  return { toggle, darkMode: value };
};
Enter fullscreen mode Exit fullscreen mode

The hook listens for any changes to the dark mode and adds or removes the .prose-dark class as required. With the hook running on every page I escape the useEffect if the required HTML element isn't present.

Discussion (3)

Collapse
jjranalli profile image
jj_ranalli

I personally use next-themes, but also useDarkMode is a great solution! Have you considered using Nightwind? It's a Tailwind plugin I made to make dark mode even more powerful

(If you're curious to learn more, I also recently wrote a post about it)

Collapse
enochndika profile image
enoch ndika • Edited on

You can just use next-themes package which makes it easier to toggle dark mode without any flash in server side with Next.js

Collapse
dlw profile image
Darren White Author

Thanks, that looks interesting. I'll give it a go